0

I have a Web API that takes 3 parameters (e.g: int EID, string MUN, string MUP) and then return a JSON like this:

[
    {
        "MemberID": 71,
        "MemberExamID": 1
    }
]

Now I want to alert 'MemberID' in my React-JS project, when the user click on 'Submit' button. and this is part of my React-JS codes too:

export class LoginModal extends Component {
    constructor(props) {
        super(props);
        this.state = { MemberID: 0}
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit(event) {
        event.preventDefault();
        fetch(process.env.REACT_APP_API + 'MemberExamValidation', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                EID: event.target.ExamID.value,
                MUN: event.target.EDT_Username.value,
                MUP: event.target.EDT_Password.value
            })
        })
        .then(res => res.json())
        .then(data => {
            this.setState({ MemberID: data.MemberID });
            alert(this.state.MemberID);
         },
         (error) => {
             alert('Erroe');
         })
    }
Germa Vinsmoke
  • 3,541
  • 4
  • 24
  • 34

1 Answers1

0

The the setState function is async which means if you try to read the value right after you set it, it'll not work the way you've done it. Instead try this -

this.setState({
  MemberID: data.MemberID,
}, () => {
  // read value here
  alert(this.state.MemberID)
});

Read more about setState callback here - https://reactjs.org/docs/react-component.html#setstate

Bikas
  • 2,709
  • 14
  • 32
  • There can be issue in your code. Have a look at Codesandbox here - https://codesandbox.io/s/rough-flower-czk25?file=/src/App.js – Bikas Feb 14 '21 at 12:52