Ritik Ranjan
Ritik Ranjan

Reputation: 23

getting problem on using useContext in react?

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

thing i have tried

I am getting same problem even when I use typescript.

but none of the above helped.

Upvotes: 1

Views: 2568

Answers (3)

Aliston Gomes
Aliston Gomes

Reputation: 1

in index.js/main.js file

<emailProvider/> <App/> <emailProvider>

this helped me

Upvotes: 0

Nithin - Techidiots
Nithin - Techidiots

Reputation: 103

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>
  );
}

Upvotes: 0

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

Upvotes: 0

Related Questions