Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
Is there a way to put react hooks in a function that's not function component?

I'm trying to create a function that is not a component nor hooks that's callable on speficic event. Let's say i have a simple function that post a data using axios and i want to use navigate after the post is successfull. Here's the example

export const authLogin = (email, password) => {
    const config = {
        withCredentials: true,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-CSRFToken': Cookies.get('csrftoken')
        }
    }

    let navigate = useNavigate();

    return dispatch => {
        console.log('Masuk ke dalam auth file');
        dispatch(authStart());
        axios.post('/log_in/', {
            email: email,
            password: password
        }, config)
            .then(res => {
                if (res.data.error) {
                    alert(res.data.error)
                    dispatch(authFail(res.data.error))
                }
                else {
                    const token = res.data.key;
                    const expirationDate = new Date(new Date().getTime() + 3600 * 1000);
                    localStorage.setItem('token', token);
                    localStorage.setItem('expirationDate', expirationDate);
                    dispatch(authSuccess(token));
                    dispatch(checkAuthTimeout(3600));
                    alert('login berhasil')
                    navigate("/", { replace: true });
                }

            })
            .catch(err => {
                alert(err);
                dispatch(authFail(err))
            })
    }
}

I have an error that says enter image description here

but when i try to change the function name with an uppercase letter, another problem occured, how do i resolve this problem?enter image description here

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

A hook must be attached to a fiber which is directly attached to the React component tree. You CANNOT use hooks outside the component tree because React can't keep track of them (this is why hooks must always be run in the same order, and can't be conditional, because React keeps track of their state internally).

The only time you can use a hook outside of a component, is from another hook.

In short, you must be able to draw a straight line back from the hook call to React rendering the component tree. If you cannot, then it's an invalid hook call.

THE SOLUTION

...in your case - is to simply pass in the navigate function to your action as a parameter:

const MyComponent = () => {
 
   const navigate = useNavigate();

   const doSomethingHandler = () => {
      dispatch(authLogin(email,password,navigate))
   }

}


const authLogin = (email,password,navigate) => {

    // ...do your action and call the `navigate` parameter
    // when you need to
}

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda