Alan911B
Alan911B

Reputation: 45

React Hook "useNavigate" is called in function

i am trying to create a token, when its expired ... redirect it to login page. but as soon as i add navigate('/login') i am getting an error Error-"React Hook "useNavigate" is called in function"

what am i doing wrong? how can i navigate to login page?

const me = async (token) => {
const navigate = useNavigate()
  let config = {
    headers: {
      Authorization: "Bearer " + token
    }};
    
  try {
    const response = await axios.get(API_URL + 'api/users/me', config)
  } catch (error) {
    logout()
    reset()
    // navigate('/login')
  }
}

Upvotes: 2

Views: 2820

Answers (2)

Walens
Walens

Reputation: 130

function name should start with uppercase, try change 'me' to 'Me'.

Upvotes: 3

brianmarco
brianmarco

Reputation: 353

So, useNavigate is a React Hook. As such it can't be called within a nested function.

Here's a quick and dirty example of something you might be able to try (based on the snippet you provided in your question).

https://codesandbox.io/s/usenavigate-example-itk3on?file=/src/Me.tsx

You'll see an example of calling useNavigate within the top level React function in that sandbox.

You might want to take a look at https://reactjs.org/docs/hooks-rules.html for further reference.

Upvotes: 1

Related Questions