David Luong
David Luong

Reputation: 443

Cannot read states in Redux with React Hooks, Cannot read property '_id' of null

I have a MERN Web-app, which I am learning React Hooks.

What I am trying to do : Access the states in my Redux.

When i refresh the page, The error : TypeError: Cannot read property '_id' of null

I am not able to access it when I clearly see the states in my redux developer tools. I have tried console.log(auth.isAuthenicated) but it returns null. However, when I do console.log(auth), it returns [object,object]. Which confuses me because I can't get inside.

Currently, I am researching and will look into react-persist. I was wondering if anyone can help me with my issue without react persist or explain why it might be a good idea to use it.

My redux :

token(pin):"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlNDFmYTNhOWIwZjk0NmU5N2Q5MmY4MiIsImlhdCI6MTU4Mzk0NzA5MSwiZXhwIjoxNTgzOTUwNjkxfQ.pysX20n4cxKK5NqcXPosIejSvCN3pbcSNpQvEOX9kBE"
isAuthenticated(pin):true
isLoading(pin):false
_id(pin):"5e41fa3a9b0f946e97d92f82"
name(pin):"admin"
email(pin):"admin@gmail.com"
date(pin):"2020-02-11T00:50:02.183Z"
__v(pin):0 

snippets of my code :

import React, { useState, useEffect } from "react";
import { TiDelete } from "react-icons/ti";
import Restaurants from "../Restaurant/Restaurants";
import NutritionalGraphs from "../D3Graphs/NutritionalGraphs";
import { connect, useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { addItem, deleteItem } from "../../../actions/itemActions";
import IngredientsPredictions from "../Predictions/IngredientsPredictions";
import { loadUser } from "../../../actions/authActions";

import { createSelector } from "reselect";

const UserProfile = props => {
  const dispatch = useDispatch();

  const [newUserFavorite, setNewUserFavorite] = useState("");
  const [favArray, setFavArray] = useState([]);
  const tokenRecognized = useSelector(state => state.auth.token);

  // const userID = useSelector(state => state.auth.user._id);
  const auth = useSelector(state => state.auth);

  const userStates = createSelector();
  // name
  // name => props.auth.user.name,
  // userID => props.auth.user._id
  // foodFavoritesArray => foodFavoritesArray.state.item.items

  useEffect(() => {
    dispatch(loadUser(tokenRecognized));
    // console.log(userStates.userID);
    console.log(auth.isAuthenicated);

    axios
      // .get(`/api/items/item/${userStates.userID}`)
      .get(`/api/items/item/${auth.user._id}`)
      .then(res => {
        return res.data;
      })
      .then(json => {
        setFavArray(json);
      })
      .catch(err => console.log(err));
  }, [userStates.userID]);
  console.log(favArray);

it is breaking at : .get(`/api/items/item/${auth.user._id}`):

Big thank you for the read.

Upvotes: 0

Views: 902

Answers (1)

trixn
trixn

Reputation: 16354

You need to wait for your loadUser action to complete before you can access the data. I assume that it makes an async request. You need to that in two steps:

useEffect(() => {
    // fetch user data when component mounts
    dispatch(loadUser(tokenRecognized)); 
}, []);

useEffect(() => {
    // check if user has been fetched (will not be the case on mount)
    if (auth.user) {
        axios
        .get(`/api/items/item/${auth.user._id}`)
        .then(res => {
            return res.data;
        })
        .then(json => {
            setFavArray(json);
        })
        .catch(err => console.log(err));
    }
}, [auth.user]); // perform this when `auth.user` changes

Upvotes: 1

Related Questions