How to use useHistory() hook outside functional component in React js?

Viewed 1780

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)

3 Answers

You can just pass history as a parameter like this

...inside function component
const history = useHistory();
console.log(history)
//call function here
yourFunc(history)

You can also use document.location.href = '/help'

Good question. We have so many api calls and have to handle those responses accordingly. What I want to mention here is the close relation between routing and UI(for example, ProfilePage component).

According to Hook rules, we can't use hook function outside the React component, so we have to use the ways like @Zhang and @istar's answers.

But split the routing and component isn't a good practice. Of course some developers use routing config file for routing, but changing the url is usually being done in component. I think routing is also one part of component.

So I want to recommend you that do the routing inside the component. Please take the result of response handling function and do the routing according to its result.

Related