Jlarkin
Jlarkin

Reputation: 29

How to run a function and then setState using React

I am new to React and am having difficulty.

In my Login Component I have the user click login which points to the handleLogin function

  const handleLogin = () => {
    (userService.login(username, password);

    setUsername('');
    setPassword('');
  
  };

this then calls the login functon within the userService:

class UserService {


  login(username, password) {
    Axios.post('http://localhost:3001/login', {
      username: username,
      password: password,
    }).then((response) => {
      if (response.data.message) {
        return response.data.message;
      } else {
        localStorage.setItem('token', response.data.token);
        localStorage.setItem('user', response.data.result[0].id);
        return response.data.result[0];
      }
    });
  }

}

export default UserService;

After calling this function I want it to update the state which will rerender the form and change my login button to a logout button. However, every time I run it it is resetting the state first and then performing the userService.login function. How can I correct this?

Upvotes: 2

Views: 129

Answers (1)

DrunkOldDog
DrunkOldDog

Reputation: 748

The login method from your class is an asynchronous event, so to make it work you have to wrap the loggin method with an "async" expression:

async login(username, password) {
 ...
}

And then, you can turn your handleLogin function into an asynchronous function too using the async/await expressions:

const handleLogin = async () => {
    await userService.login(username, password);

    setUsername('');
    setPassword('');
  
};

What this does is first wait the login method to be finalized and then set the state to the empty values. I'll recommend to you to return the new values in the "login" method instead of setting them in the localStorage so you can obtain them directly from the returned values in the handleLogin "userService.login" call.

Upvotes: 2

Related Questions