0
votes

I have stuck with some issue while using hooks with redux using useDispatch, useSelector. same issue with mapDispatchToProps, mapStateToProps.

I have attached sample code below.based on that the issue is.. On button click(saveSettings() method) when i tried to call an action method using dispatch(cn_fetchData()) after getting the success result from another dispatch(cn_saveData()) call, it will not wait to get the success message using useSelector "cn_saveDataValue ". Tried to use async await. but it failed.

const dispatch = useDispatch();
const cn_fetchData = (appId) => dispatch(_fetchcn_appValues(appId));
const cn_saveData = (appId, testData) => dispatch(_saveSettings(appId, testData));

const cn_saveDataValue = useSelector(state => state.AppReducer.cn_saveDataValue);
const cn_appValues = useSelector(state => state.AppReducer.appData);

const saveSettings = async () => {
    try {
        await cn_saveData(
            appData._id,
            testData,
        );
        // **Issue is here. Its not waiting to get cn_saveDataValue to true after updating to the database using "await cn_saveData"**
        if (cn_saveDataValue) {
            await cn_fetchData(appData._id); // Fetch updated data from the database using action, reducer
        }
    } catch {
        console.log("Err !! Please Try again !");
    }
}

I am using action and reducer. Set response from reducer. if (cn_saveDataValue) getting false first time when save settings. so await cn_fetchData(appData._id); method not firing.

1

1 Answers

0
votes

Because cn_saveData is a sync function, not an async fn so it can not wait to get cn_saveDataValue to true after updating

You should use useEffect in this case:

  useEffect(() => {
    if (cn_saveDataValue) {
      cn_fetchData(appData._id);
    }
  }
  }, [cn_saveDataValue]);