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