My Provider File of Context API (Exp file)
import react form 'react';
import {createContext} from "react";
export const ContextforFile = createContext();
export function ContextData(props){
let rdata=props.data
return(
<>
<p>{rdata}</p> //I am able to Get the Data here NO ISSUES TILL HERE
<ContextforFile.Provider value={rdata} >{props.children}</ContextforFile.Provider>
</>
);
}
function A() {
return (
<div>
<ContextData data="Sara" />
</div>
);
}
export default A;
My App.js File
import Exp, { ContextData } from './afterlogin/patirel/patmain';
import Experiment from './experi';
import {Routes,Route} from 'react-router-dom';
import * as React from 'react';
function App() {
return (
<ContextData>
<div>
<Routes>
<Route index element={<Exp/>} />
<Route path="/experi" element={<Experiment/>} />
</Routes>
</div>
</ContextData>
);
}
export default App;
only props.data value is not coming here while other values can be easily obtained This is Experi file Where I want to get my values my Consumer File
import * as React from 'react';
import { useContext } from 'react';
import { ContextforFile } from './afterlogin/patirel/patmain';
export default function Experi(){
const first= useContext(ContextforFile);
return(
<div>
<h1>ISSUE is Here Other VALUES are COMING BUT NOT props.data: {first}</h1>
</div>
);
}
Please help! It's been days and i cannot figure out what am i missing? How can I resolve it?
CodePudding user response:
Your function ContextData
does not return anything. Yoo should return the ContextforFile.Provider
CodePudding user response:
The possibility of getting the undefined value could be many things.
for Example:
maybe, you are getting undefined from props.data. maybe because you are not providing the default value to createContext.
try the following steps these may help you.
- You must pass the default value to createContext if needed.
export const ContextforFile = createContext([value it could be any thing like array, string or object etc.]);
- when you create a hook you have to write the code something like this.
Your version:
const first= useContext(ContextforFile);
recommended version:
const useFirst= () => useContext(ContextforFile);
- Use this hook something like this.
const first= useFirst()
here you can find the difference: sandbox example