I am refactoring a MERN app to use hooks and context, so I'm changing class components to functions. One component has a form that changes state based on the keystrokes in an input field, like:
class CreateAccountComp extends Component {
constructor(props) {
super(props);
this.state = {
firstName: null,
lastName: null,
email: null,
password: null,
githubID: null,
};
}
handleSubmit = (e) => {
e.preventDefault();
this.props.handleInputChange();
API.getsync(this.state.githubID, this.state.firstName, this.state.lastName, this.state.email);
...
})
};
handleChange = (e) => {
e.preventDefault();
const { name, value } = e.target;
...
this.setState({ [name]: value }, () => null);
};
....
This works after the callback was added to the 'this.setState' statement.
The new component looks like this:
const CreateAccountComp = (props) => {
const [state, setState] = useState({
firstName: null,
lastName: null,
email: null,
password: null,
githubID: null,
});
const handleSubmit = (e) => {
e.preventDefault();
console.log("HMMMM leaving CreateAccountcomp");
props.handleInputChange();
API.getsync(state.githubID, state.firstName, state.lastName, state.email);
...
};
const handleChange = (e) => {
e.preventDefault();
const { name, value } = e.target;
...
setState({ [name]: value });
};
Now, I can't use a callback to deal with the asynchronous setState statement, and the state properties being passed to the API.getsync() function are undefined.
My research comes up with examples of using async/await or useEffect, but they all deal with single calls to an external api. Here, I'm running handleChange to render the keystrokes into the input fields in a form, then running handleSubmit via onSubmit to execute a function to update the database based on the state values. Is there a way to update state properly in this function component?