'react dispatch function after useSelector variable available

I want to dispatch a function after useSelector function get called.

This is my code

 const profile = useSelector(
    ({ x}) => x.profile,
  );


  useEffect(() => {
     dispatch(fetchX(y, setXStatus)); // this is getting called before profile is available 
  }, [dispatch,y]);

The issue is when dispatch(fetchX(y, setXStatus)); getting executed profile variable is not properly set.Is there a way to run fetchX after profile is set.



Solution 1:[1]

If by "after useSelector function is called" you mean "whenever profile changes," you need to add profile to the dependency array. If profile can be null (or similar) and you need a profile before you can do the dispatch, you'll need a guard.

Something along these lines:

const profile = useSelector(
    ({ x}) => x.profile,
);

useEffect(() => {
    if (profile) { // <?????? Guard
        dispatch(fetchX(y, setXStatus));
    }
}, [dispatch, y, profile]);
//               ^^^^^^^????? Dependency

Note, though, that this effect callback will be called every time dispatch, y, or profile changes. dispatch probably never changes, but I don't know about y or profile.

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