I am trying to pass data from a JSON file to a component with useContext:
import sessionData from '../session.json';
import React from 'react';
export const SessionContext = React.createContext(sessionData);
export const SessionProvider = SessionContext.Provider;
export const SessionConsumer = SessionContext.Consumer;
console.log('session data', sessionData); //console log ok
Next I am passing it into a class component
static contextType = SessionContext;
componentDidMount() {
const sessId = this.context;
console.log('steps', sessId); // log ok
}
render() {
return <SessionProvider value={sessId}> //value returns undefined.
<Child A />
<Child B />
<Child C />
</SessionProvider>;
}
In the first two code blocks shown, my data returns fine. Now I want to pass it to the child components (which are functional component). However, when I try to pass a value to the session provider <SessionProvider value={sessId}
, the value returns as undefined.
I've seen other examples where the value is passed directly into the component like ``{sessId.name}. However, if I'm just trying to make
sessId``` available to all the child components.
sessId doesn't exist
The error that you're getting is likely that
sessId
doesn't exist.sessId
exists in thecomponentDidMount
method but not in your render method.You would need to create that variable in your render method with
this.context
, just like you did incomponentDidMount
.You don't need the provider
But... you don't need the provider there. When you provide an initial value to
React.createContext
, then that becomes a default value, so you can just consume it with the children and the data will be there.You don't need context
However, if you're just using static JSON, then you don't need context here at all: just import the JSON file into each of the children and use it there.