Search code examples
reactjsreduxnext.js

reading state of redux


Could someone explain why I am able to read user.token_type but its undefined if trying to read user.user.id

  const user = useSelector(
    (state) => state.userreducer.user.token_type /* WERT AUS REDUX DB*/
  );

Output: bearer

  const user = useSelector(
    (state) => state.userreducer.user.user.id /* WERT AUS REDUX DB*/
  );

Output: TypeError: Cannot read property 'id' of undefined

enter image description here


Solution

  • I just read your issues and I understood the reason. Although the redux loads user data when your app is rendered, it will take some time. So user is null in initial state. Finally token_type property of null(user) can't be accessed.

    In order to solve this problem, you need to use this code.

      const user = useSelector(
        (state) => state.userreducer?.user?.token_type
      );
    
    const user = useSelector(
        (state) => state.userreducer?.user?.user?.id
      );
    

    Thank you for reading my advice.