React reusable function that sets useContext

Viewed 158

My current function handleLogin() takes care of calling to an API that sets the state of loggedIn to true inside the then() block like so.

function handleLogin() {
if(username.length && password.length) {
  axios({
    method: 'post',
    url: `apiurl...`,
    data: JSON.stringify({
        
    }) 
    }).then((response) => {
        setResponse()
        setLoggedIn(true)
        setLogMsg(response.data.data)
        console.log(response.data.data)
    }, (error) => {
    console.log(error) 
    })
}
else {
  alert(`Nom d'utilisateur ou mot de passe n'est pas valide`)
}

}

This works fine. But i would like to abstract this function and use it inside a reusable component. The problem is i cannot use react's context api inside a non-react component, and so i cannot set the context/state accross my app.

When i try to use this function inside its own component i get the error: "Invalid hook call. Hooks can only be called inside of the body of a function component"

Are there any solutions to this problem?

0 Answers
Related