0

I'm trying to do an API call triggered only when the user clicks on the submit button

This is in a user login context where the parent's component state gets changed.

import React from 'react';
import {Button, FormGroup, FormControl, ControlLabel} from "react-bootstrap";
import './login.css';

export default class loginForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: '',
      answer:[],
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  async handleSubmit(event) { 
    const jso = JSON.stringify({
      username: this.state.username,
      password: this.state.password
    })
    const response = await fetch("https://app.herokuapp.com/authentication", {
      method: 'POST',
      mode: 'cors',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: jso,
    })

    const json = await response.json()
       
    this.setState({answer:json});

    //check if user is authentificated
    alert("Server Answer : "+ this.state.answer.answer);
    if(this.state.answer.answer.localeCompare('true') == 0){
      this.props.app.setState({auth: true});
      sessionStorage.setItem('auth', true);
    }
    else if (this.state.username != ""){
      alert("INCORRECT USERNAME PASSWORD ");
    }
  }


  render() {
    
    return (<div className="Login">
      <form onSubmit={this.handleSubmit}>
        //part omitted because not relevant for this question
        <Button bsSize="small" color="primary" type="submit">
          Login
        </Button >
      </form>
    </div>)
  }
}

My question: Is it possible to do something like this or I absolutely need to use componentDidMount() ?

I've been struggling / searching about this for too much time now and I still can't find a way to make it work.

1
  • In this case, you should use promise instead async/await Commented Oct 3, 2018 at 3:50

1 Answer 1

1

It is possible to do this. From what I can see, you're having problems once you reach the //check if user is authentificated. This happens because react's setState is asynchronous.

In order to access the state right after it's modified, the setState function takes an optional callback function, sou you could try writing your code like this:

this.setState({answer:json}, () => {
    //check if user is authentificated
    alert("Server Answer : "+ this.state.answer.answer);
    if(this.state.answer.answer.localeCompare('true') == 0){
      this.props.app.setState({auth: true});
      sessionStorage.setItem('auth', true);
    }
    else if (this.state.username != ""){
      alert("INCORRECT USERNAME PASSWORD ");
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer! However, it only works 1 out of 10 times.... Which means I still have a asynchronous call problem... Do you think promise may be better ?
It's definitelly worth a try, I'd say. I can't really see what else could be the problem though...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.