0
votes

I have a simple react app in which i have to use useContext.

(btw im using vite + react)

here is my code for Context.jsx

import React, {useContext} from 'react';

const emailContext = React.createContext();

export const useEmail = () => useContext(emailContext);

export const emailProvider = ({children}) => {
  const currentUser = "None";

  const value = {
    currentUser
  }

  return(
    <emailContext.Provider value={value}>
      {children}
      </emailContext.Provider>
  )
}

and heres how i am using the context

import "./styles.css";
import { useEmail } from "./Context/Context"

export default function App() {

  const {currentUser} = useEmail();

  return (
    <div className="App">
      <h1>Hello CodeSandbox {currentUser}</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

I am sure why I am getting error in this code.

some of the errors that I am getting

  • _useEmail is undefined (latest)
  • currentUser user is undefined

thing i have tried

  • Initialized createContext with some initial value (only intial value is visible).
  • using useContext() directy in the App.js (useContext(emailContext) return undefined)
  • instead of {children} used <children/>.
  • used useState instead of const currentUser in emailProvider

I am getting same problem even when I use typescript.

but none of the above helped.

2

2 Answers

0
votes

You should wrapping app with <emailProvider></emailProvider> to using data in value={value}. Now it gets undefined from const emailContext = React.createContext();

0
votes

Below code may help you analyse the flow , also check link for more details https://medium.com/technofunnel/usecontext-in-react-hooks-aa9a60b8a461

use useContext in receiving end

 import React, { useState } from "react";

var userDetailContext = React.createContext(null);

export default function UserDetailsComponent() {
  var [userDetails] = useState({
    name: "Mayank",
    age: 30
  });

  return (
    <userDetailContext.Provider value={userDetails}>
      <h1>This is the Parent Component</h1>
      <hr />
      <ChildComponent userDetails={userDetails} />
    </userDetailContext.Provider>
  );
}

function ChildComponent(props) {
  return (
    <div>
      <h2>This is Child Component</h2>
      <hr />
      <SubChildComponent />
    </div>
  );
}

function SubChildComponent(props) {
  var contextData = React.useContext(userDetailContext);
  return (
    <div>
      <h3>This is Sub Child Component</h3>
      <h4>User Name: {contextData.name}</h4>
      <h4>User Age: {contextData.age}</h4>
    </div>
  );
}