Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading