I have a component fetching a API service that returns JSON. The service works, but the state on returns the json in the fetch after the second alert(this.state.questions); below.
My understanding of the execution stack of React is it shouldn't do that (I'm reasonable new to React). Or is it that state has a limited lifestyle time?
import React from 'react';
import { ConversationalForm } from 'conversational-form';
export default class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
questions: []
};
this.submitCallback = this.submitCallback.bind(this);
}
componentDidMount() {
fetch('http://localhost:3000/api/questions')
.then((response) => response.json())
.then((responseJson) => {
this.setState({questions:JSON.stringify(responseJson)}, () => console.log(this.state.questions)); // Works fine, log has the json response
alert(this.state.questions); // Returns expected JSON - runs after the next alert
})
alert(this.state.questions); // returns undefined - runs first
this.cf = ConversationalForm.startTheConversation({
options: {
submitCallback: this.submitCallback,
showProgressBar: true,
preventAutoFocus: false,
},
tags: this.state.questions // returns undefined
});
this.elem.appendChild(this.cf.el);
}
submitCallback() {
var formDataSerialized = this.cf.getFormData(true);
console.log("Formdata, obj:", formDataSerialized);
this.cf.addRobotChatResponse("Your are done. Grab a well deserved coffee.")
}
render() {
return (
<div>
<div
ref={ref => this.elem = ref}
/>
</div>
);
}
}