This is my custom hook:
function useFetch({url = '', method = 'get', body}) {
const [data, setData] = useState(null);
useEffect(() => {
try {
(async () => {
const data = await fetch[method](url, body);
setData(data);
})();
} catch (err) {
console.log("An error ocurred")
}
}, [url, method, body]);
return [(!data && <LoadingIcon />, data, setData];
}
I want to execute setUserFeedbackMsg("An error ocurred"), which is part of a context component, every time an error ocurrs on any instantiation of the hook. Of course I could do it manually on every component that uses the hook, but I'm wondering if there's a way to condense it all in one place. Thank you!
Compose your context (global state) into a hook that components and other hooks can access.
Here's what's happening here in a nutshell:
useUserFeedback.useUserFeedbackContext. This way, we can easily access the state getter and setter in components and, importantly, other hooks!useUserFeedbackContexthook in ouruseFetchhook to set the message state to an error assuming there is one.useUserFeedbackhook inuseFetch? The answer is an important concept in React - hooks share behavior, while Contexts share state. If we simply tried to use theuseUserFeedbackhook, each time we calleduseFetchwould result in a new''messagestate object. Using Context, we share oneuseUserFeedbackinstantiation across the board.