Reputation: 151
Can I use useRef() for the purpose to memoize an object from a custom hook? Because without that when if I use that returned object from the hook as a useEffect dependency I get an infinity loop of requests.
Example of my code that I use now:
const apiHook = useRef({})
apiHook.current = useRequest(
'http://someapi',
{
onSuccess: (data) => {
console.log(data)
}
}
)
useEffect(() => {
apiHook.current.run()
}, [])
Upvotes: 0
Views: 880
Reputation: 97
First params for useRequest is a function who return a promise : () => axios(url)
Example with axios : Here
Example with custom useApi : Here
Upvotes: 1
Reputation: 169388
You probably want something like
function Component() {
const apiResp = useRequest('http://someapi');
useEffect(() => {
console.log(`New data: ${apiResp.data}`);
}, [apiResp.data]);
}
i.e. only use the data of the useRequest
as a dependency.
Upvotes: 2