Hi,
I’m trying to pass a state via context, to use it in another component.
export const DataContext = React.createContext();
export class DataProvider extends Component {
constructor(props) {
super(props);
{console.log(this.props.continent)}
this.state = {
continent: this.props.continent,
};
}
updateState() {
this.setState = {
continent: this.props.continent,
};
}
render() {
return (
<DataContext.Provider value={{ state: this.state }}>
{this.props.children}
</DataContext.Provider>
);
}
Here, the consol.log logs the correct
However, I do pass this to one other component, where I’d like to use this state.
static contextType = DataContext;
componentDidMount() {
console.log(this.context)
}
In this component, the state is undefined. It is NOT undefined if I specify the state in the constructor for the context, such as:
constructor(props) {
super(props);
{console.log(this.props.continent)}
this.state = {
continent: "ABC",
};
Do anyone have any idea about what I’m doing wrong?
I’ve wrapped the component with my context in App.
Everything works, except, that the state becomes undefined as soon as it’s a variable.
Edit:
It may have to do with the component, which passes the prop in the beginning never gets called when I enter the next component.
I’m trying to pass a string of a continent. Just doing this:
<DataProvider continent={["Africa"]} />