How to navigate("*") inside child const instead of parent component?

I have this place in my app.js router:

        <Router>
          <Routes>
            <Route path="/" element={[<Navigation key={0}/>, <Home key={1}/>]} />
            <Route path="*" element={[<NotFound/>]} /> 
          </Routes>
        </Router>

This is so any unrecognised requests go to my 404 (NotFound)

Now I want to hook requests up to this so if an element is required to have data, and the requests returns 404, it should redirect to 404.

Here is my parent component:

  useEffect(() => {
    fetchData()
  }, [])

  async function fetchData() {
      var data = (await redirectGetRequest(`Quizzes/${quizId}`))
      setQuiz(data)
  }

Here is my request component:


export const redirectGetRequest = async (endpoint) => {
    const navigate = useNavigate();
    var result = ""
    var errorMsg = {};
    try {
        const get_response = await Axios.get(`${window.ipAddress.ip}/${endpoint}`);
        if (get_response.data !== null && get_response.status === 200) {
            result = get_response.data;
        }
        else {
            // handle error here
        }
    }
    catch (err) {
        if (err.response?.status === 404) { navigate('*') } // doesnt like this
        else { errorMsg = 'alternative error' }
        console.log("error",err)
    }
    return (result);
}

This is the problem, it doesn’t like navigate or useNavigate in this element.

I don’t want to redirect in the parent component as that would defeat the purpose of handling all request errors and redirects in a single location.

the error I get is:

Line 28:22:  React Hook "useNavigate" is called in function "redirectGetRequest" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use" 

changing redirectGetRequest() in the parent and the child request similarly to useRedirectGetRequest() doesnt fix this issue.

>Solution :

Your function redirectGetRequest breaks the rule of hooks. Hooks must be called from React Function components. Instead, you are calling a hook from a function.

The solution is to update redirectGetRequest to take navigate as a param.

export const redirectGetRequest = async (navigate, endpoint) => {
    var result = ""
    var errorMsg = {};
    try {
        const get_response = await Axios.get(`${window.ipAddress.ip}/${endpoint}`);
        if (get_response.data !== null && get_response.status === 200) {
            result = get_response.data;
        }
        else {
            // handle error here
        }
    }
    catch (err) {
        if (err.response?.status === 404) { navigate('*') } // doesnt like this
        else { errorMsg = 'alternative error' }
        console.log("error",err)
    }
    return (result);
}

Then call useNavigate hook inside your Component, and pass as a param.

  const navigate = useNavigate();

  useEffect(() => {
    fetchData()
  }, [])

  async function fetchData() {
      var data = (await redirectGetRequest(navigate, `Quizzes/${quizId}`))
      setQuiz(data)
  }

Leave a Reply