Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React get state from Redux store within useEffect

What is the correct way to get state from the Redux store within the useEffect hook?

    useEffect(() => { 
        const user = useSelector(state => state.user);
    });

I am attempting to get the current state within useEffect but I cannot use the useSelector call because this results in an error stating:

Invariant Violation: Hooks can only be called inside the body of a function component.

I think I understand why as it breaks one of the primary rules of hooks.

From reviewing the example on the Redux docs they seem to use a selectors.js file to gather the current state but this reference the mapStateToProps which I understood was no longer necessary.

Do I need to create some kind of "getter" function which should be called within the useEffect hook?

like image 442
Sheixt Avatar asked Sep 29 '19 20:09

Sheixt


Video Answer


3 Answers

Don't forget to add user as a dependency to useEffect otherwise your effect won't get updated value.

const user = useSelector(state => state.user);
useEffect(() => { 
   // do stuff     
}, [user]);
like image 161
Motomoto Avatar answered Oct 20 '22 06:10

Motomoto


You can place useSelector at the top of your component along with the other hooks:

const MyComponent = () => {
  ...
  const user = useSelector(state => state.user);
  ...
}

Then you can access user inside your useEffects.

like image 44
Hamza El Aoutar Avatar answered Oct 20 '22 04:10

Hamza El Aoutar


I found using two useEffects to works for me, and have useState to update the user (or in this case, currUser).

const user = useSelector(state=>state.user);
const [currUser, setCurrUser] = useState(user);

useEffect(()=>{
  dispatch(loadUser());
}, [dispatch]);

useEffect(()=>{
  setCurrUser(user);
}, [user]);

You have to use currUser to display and manipulate that object.

like image 21
m007 Avatar answered Oct 20 '22 05:10

m007