3

I'm trying to get state and setState from the Store file but I get undefined. What's happening, and how do fix it?

import React, {createContext, useState} from 'react'
import Header from './Header'

export const Data = createContext()


function Store() {
  const [state, setState] = useState(false)
  const  value = {state, setState}

  return (
    <Data.Provider value={value}>
      <Header/>
    </Data.Provider>
  )
}

export default Store
import React, { useContext} from "react";
import { Data } from "./Store";

function Header() {
  const Store = useContext(Data)
  
  console.log(Store) // I get undefined

  return (
    <div>
    </div>
  );
}

export default Header;
0

1 Answer 1

1

You are creating Store, but never calling it, that's the problem. Wrap App component inside Store and it would work. Working example of your link here.

index.js:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import Store from "./store";
import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <Store>
      <App />
    </Store>
  </StrictMode>
);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.