Search code examples
reactjsuse-reducer

Use state after dispatch finishes


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();
}

Solution

  • 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.