I have a function in a separate js file that checks status codes received from Api requests, and depending on the code this function needs to perform some actions:
function handleResponseCodes(res) {
try {
if (res.status ===200 ) {
return res.json();
} else if (res.status === 404) {
// here I need to redirect to /help
} else if (!res.ok) {
alert("Error")
} else {
if (res.ok) {
return res.data;
}
}
} catch (error) {
console.log(error);
}
}
and then this function is used like this with fetch requests.( project will have 100+ api requests so this way makes the process easy to follow).
fetch(url, obj)
.then((res) => handleResponseCodes(res)
If res.code === 404 I need to redirect the user to /help url, problem is that when I try to use useHistory() hook like this:
import {useHistory) from 'react-router-dom'
const history = useHistory()
//and in the function
else if (res.status === 404) {
// here I need to redirect to /help
history.push("/help")
I get error saying that useHistory hook must be used only in functional components. Is there a React way to redirect/push user to the /help from outside functional component?(basically from inside a function)