Ritesh Gupta
Ritesh Gupta

Reputation: 65

TypeError: statevalue is undefined

I am making a comments component wherein I get data from a local stored json file. I import the data in the variable data and set its corresponding fields to my state values. But when I pass the data through the context, it says that it is undefined.

data.json

{
  "currentUser": {
    "image": { 
      "png": "./images/avatars/image-juliusomo.png",
      "webp": "./images/avatars/image-juliusomo.webp"
    },
    "username": "juliusomo"
  },
  "comments": [
    {
      "id": 1,
      "content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
      "createdAt": "1 month ago",
      "score": 12,
      "user": {
        "image": { 
          "png": "./images/avatars/image-amyrobson.png",
          "webp": "./images/avatars/image-amyrobson.webp"
        },
        "username": "amyrobson"
      },
      "replies": []
    }
  ]
}

this is how I store and pass data context.js

import data from "./data";

const AppContext = React.createContext();

const AppProvider = ({ children }) => {
  const { comments, setComments } = useState(data.comments);
  const { currUser, setCurrUser } = useState(data.currentUser);
  return (
    <AppContext.Provider value={{ comments, currUser }}>
      {children}
    </AppContext.Provider>
  );
};

this is where I get the error App.js

import { useGlobalContext } from "./context";
const App = () => {
  const { comments, currUser } = useGlobalContext();
  ...
}

this is the error exactly

Upvotes: 2

Views: 182

Answers (1)

Drew Reese
Drew Reese

Reputation: 202605

The useState hook returns an array, not an object. Array destructuring assignment is used. First element is the state value, the second is the state updater function.

React.useState

const AppProvider = ({ children }) => {
  const [comments, setComments] = useState(data.comments);
  const [currUser, setCurrUser] = useState(data.currentUser);

  return (
    <AppContext.Provider value={{ comments, currUser }}>
      {children}
    </AppContext.Provider>
  );
};

Upvotes: 2

Related Questions