Issue with waiting for dispatch to complete before running the next function in React Native

199 Views Asked by At

I have a function onPressItem in a React Native component that dispatches an action using Redux, and then navigates to another screen using pushScreenOnFormScreen. I want to ensure that the dispatch action (FormActionLoadFormData) is completed before executing the pushScreenOnFormScreen function. I have tried using await with async on the onPressItem function, but it's giving me the error "'await' has no effect on the type of this expression." I've also attempted using useEffect, but it causes the pushScreenOnFormScreen function to be executed multiple times, leading to a navigation stack screen with the same id error/warning.

const onPressItem = async (formData: any) => {
setFormData(formData);
dispatch(FormActionLoadFormData(formData));

pushScreenOnFormScreen({
componentId: Screens.FORM_FIELDS_SCREEN,
passProps: { formData: formData, formFields: formFields },
});
};

What would be the correct way to wait for the dispatch to complete before moving on to the next function in this scenario? Any insights or suggestions would be greatly appreciated. Thank you!

Edited: This is FormActionLoadFormData

function* FormSagaLoadFormData({
                             payload,
                           }: FormTypeLoadFormData): 
 Generator<ReturnYield> {
 try {
  // Getting the auth token from store.
 const token: any = yield select(userSelectorAuthenticationToken);

// Here the payload is just the { id: 00, name: '', ... }.
// @ts-ignore
const id: number = payload ? (payload.id ? payload.id : -1) : -1;
const result: any = yield call(ApiGetFormByID, {token, id});

let form: any = null;
try {
  form = result.data.data.form;
} catch (err) {
  //
}

if (form) {
  yield put({
    type: FORM_ACTION.REDUCER.SAVE_FORM_DATA,
    payload: form,
  });
}
 } catch (error) {
  console.log('FormSagaLoadFormData error', error);
 }
 }
1

There are 1 best solutions below

0
Vin Xi On

If you are hitting API, the correct way to handle this would be to check whether the call is successful or not. The best practice is to have a success action which will be dispatched on api call succeeding.

Then in the react component where you want to dispatch the action after it is completed, you will do

const isSuccess = useSelector(success);

const onPressItem = async (formData: any) => {
  setFormData(formData);
  dispatch(FormActionLoadFormData(formData));
}



useEffect(()=>{
            pushScreenOnFormScreen({
             componentId: Screens.FORM_FIELDS_SCREEN,
             passProps: { formData: formData, formFields: formFields },
  });
  },[success])