Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useNavigate - Invalid hook call. Hooks can only be called inside of the body of a function component

I'm using ReactJS in frontend and NodeJS in backend and I'm trying to redirect with navigate function but I'm getting the error. What should I do exactly? Where am I missing? How can I redirect if the registration form is successful?

My action:

export const signup = (formData,navigation) => async (dispatch) => {
    try {
        const { data } = await API.signUp(formData)
        dispatch({type:AUTH,payload:data})
        let navigate = useNavigate();
        navigate("/");
    } catch (error) {
        dispatch({type:SIGNUP_FAIL,payload:
        error.response && error.response.data.message ? error.response.data.message : error.message
    })
    }
}

My component:

const signUpForm = (e) => {
    e.preventDefault()
    if(!login){
        dispatch(signup(form,navigation))
    }
}
like image 274
322quick1 Avatar asked Oct 25 '25 04:10

322quick1


1 Answers

You need to move the hook outside of the function:

const signUpForm = (e) => {
    let navigate = useNavigate();
    e.preventDefault()
    if(!login){
        dispatch(signup(form,navigation,navigate))
    }
}

and:

export const signup = (formData,navigation,navigate) => async (dispatch) => {
    try {
        const { data } = await API.signUp(formData)
        dispatch({type:AUTH,payload:data})
        navigate("/");
    } catch (error) {
        dispatch({type:SIGNUP_FAIL,payload:
        error.response && error.response.data.message ? error.response.data.message : error.message
    })
    }
}
like image 60
hindus Avatar answered Oct 26 '25 17:10

hindus