Reputation: 3021
I have a react custom hook which is using useEffect
. This hook is supposed to fetch data from api using JS fetch
. Now, i want to return api or error data based on the situation and then destructure the value on the component where this hook is called. Below is the code of my custom hook
export const useGetData = (url, body) => {
const [state, setState] = useState([]);
const [errorMsg, setErrorMsg] = useState({});
useEffect(() => {
fetch(url, {
method: 'Post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
}).then(response => response.json())
setState({response});
).catch(error =>
console.error('Error:', error);
setErrorMsg(error);
return errorMsg;
);
}
}, [url, body]);
return state;
}
and here is how it has been called from react component
let data = { state: '', errorMsg: '' };
data = useGetData('url', 'body');
Now, the when the api call is success, i am able to get correct data in data
but not able to get error data in case of failure. My custom hook is early returning in case of error but the same not able to destructure in react component from where its called. What's wrong here?
Upvotes: 0
Views: 939
Reputation: 211
I believe the reason you are not seeing the error data is that you are not returning errorMsg
from your useGetData
hook.
Try this:
export const useGetData = (url, body) => {
const [data, setData] = useState([]);
const [errorMsg, setErrorMsg] = useState({});
useEffect(() => {
fetch(url, {
method: 'Post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
}).then(response => {
let data = response.json())
setData(data);
}
).catch(error => {
console.error('Error:', error);
setErrorMsg(error);
});
}
}, [url, body]);
return {data, errorMsg};
}
and in your component access the data like this:
const {data, errorMsg} = useGetData('url', 'body');
Hope this helps
Upvotes: 2