React App is giving error when using context API

Viewed 461

I am learning React and right now trying to implement the old way of working with Context API but when I try to compile I get an error.

It says :

TypeError: context is undefined. Version is 17.0.1

Here are the files I use:

Test0.js

import React from 'react';
const Test0 = React.createContext();
export default Test0;

Test1.js

import React, { Component } from 'react';
import Test0 from './Test0';

class Test1 extends Component{
render(){
    return (
            <Test0.Consumer>
                {context => (<p>This is {context.name}</p> )}
            </Test0.Consumer>
        );
}
}
export default Test1;

Test2.js

import React, { Component } from 'react';
import Test0 from './Test0';
import Test1 from './Test1';

class Test2 extends Component{
state = {
    name: 'James',
    age : 30
}
render(){
    return (
        <Test0.Provider
            value={{
                name : this.state.name,
                age: this.state.age
            }}
        >
            <Test1 />
        </Test0.Provider>
        );
}
}

export default Test2;

I then render <Test1 /> in app.js

2 Answers

You're using Test1 component which consumes Test0, a context, that you suppose to provide values, but in Test0 you're providing no value. You wrongly implemented the provider in separate Component, Test2, that you don't render so Test0 doesn't know about the provided values and it's assuming you didn't define the context.

Related