This question has already been answered:
Can you please tell how to synchronously write an object to a variable in React and immediately get it back?
For example, my react application communicates with the server and receives json data from it with different states. Based on these states, the logic of my application is built. The problem is that after receiving the response from the server and writing it to a variable, it is not possible to get this value - it is undefinded .
constructor(props) { super(props); this.state = { input: "", }; this.axiosData = {} } getServerDataGET = async (value) => { axios .get("/test.json") .then(res => { //console.log(res.data); this.axiosData = res.data; }) .catch(err => { }); }; handleChange = event => { this.setState({ input: event.target.value }); }; handleSubmit = event => { event.preventDefault(); this.getServerDataGET(); console.log(this.axiosData); } Thus, by clicking on the Submit button, a function is called that receives JSON data. Data Axios and is displayed in the console inside the Axios . This data should then be written to this.axiosData . But, as I understand it, due to the fact that the Javascript language is asynchronous, this data falls into this variable later. Therefore, inside the handleSubmit() in my undefinded . When I click the Submit button again, I see this data.
Link to an example: https://codesandbox.io/s/v6k22wx3y0