'Fetch redux state after API Call is successfully completed

I have created one dialog box for updating the user details. I have three redux states updateUserLoading, updateUserError, updateUserSuccess

I am not able to figure out how shall I call/show update successful message to user, below code is accessing old value of updateUserSuccess

  const { updateRoleSuccess, updateRoleError, updateRoleLoading }: UpdateRoleState = useSelector((state: RootState) => state.updateRole);
  
  onSubmit: async (data) => {
            await updateRole(data.editRoleId,data.priviledges);
            await fetchRoles()    

            updateRoleSuccess == true && setNotification("Role updated Successfully")

    }

I tried putting it inside useeffect too but the problem is I am using above

   useEffect(() => {
        updateRoleSuccess == true && setNotification("Role updated Successfully")
    }, [updateRoleSuccess])

But the problem is it works fine for the first time only, second time when I open dialog box it shows me "Role updated Successfully" notification because updateRoleSuccess was set to true when I made changes first time and closed box



Solution 1:[1]

You can include updateRoleSuccess in useEffect and update your notification like below.

useEffect(() => {
     if (updateRoleSuccess) setNotification("Role updated Successfully");
}, [updateRoleSuccess]);

I am guessing you are getting the status on updateRoleSuccess (true or false) based on api call.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mchowdam