0

In my code, upon submission of a form, I need to modify the state & then submit the updated state. Since useReducer is async, I can't access the updated state before form submission. How do I resolve this issue ?

const   [data, dispatch]    =   useReducer(reducer,[]);

const cleanData = () => {
  for(let entry of data){
    if(!condition) dispatch({ type: actionTypes.delete, name: entry.key});
  }
}

const onSubmitForm = e => {
  e.preventDefault();
  cleanData();
  submitData();
}
Ken White
  • 123,280
  • 14
  • 225
  • 444
  • You can use [`Promise.all()`](https://stackoverflow.com/questions/31426740/how-to-return-many-promises-and-wait-for-them-all-before-doing-other-stuff) for that. –  Oct 13 '22 at 00:59

1 Answers1

0

I resolved this by adding a boolean state linked to form submission, and then do the actual form submission via useEffect().

const   [data, dispatch]    =   useReducer(reducer,[]);
const   [submit, setSubmit] =   useState(false);

const cleanData = () => {
  for(let entry of data){
    if(!condition) dispatch({ type: actionTypes.delete, name: entry.key});
  }
}

const onSubmitForm = e => {
  e.preventDefault();
  setSubmit(true);
  cleanData();
}

const submitData = () => // Submit data to database

useEffect(() => {
  if(submit) submitData();
},[data])

Now the submitData() function receives the proper updated state.