How to fix the Context value in a Provider from the Consumer?

Viewed 22

I dont know hwo to fix this line call context provider. If I set this state on value there it shows me undefind. how to solve this ?

Error : enter image description here

context.tsx

import React, { Component } from 'react'
import { createContext } from 'react';

const Context = React.createContext('text');

//called context into Provider
export class Provider extends Component {
    state = {
        track_list: [
            {Track: {track_name:'abc'}},
            {Track: {track_name:'123'}}
        ],
        heading: 'Top 10 Tracks'
    }
  render() {
    return (
      <Context.Provider value={this.state}>
          {this.props.children}
          </Context.Provider>
    )
  }
}

export const Consumer = Context.Consumer;

package.json

"react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.4.0",
    "react-scripts": "5.0.1",
    "typescript": "^4.8.3",
1 Answers

You cannot set something that is supposed to be an object to a string. Your state takes the type

{
    track_list, // array of tracks
    heading, // a string
}

Instead you are supplying it with only one string.

const Context = React.createContext('text');

You should either set this to null, and empty object, or your default value for the context state.

const Context = React.createContext(null);

or

const Context = React.createContext({});

or if you want to supply your default state value you can do it like this:

const Context = React.createContext({
        track_list: [
            {Track: {track_name:'abc'}},
            {Track: {track_name:'123'}}
        ],
        heading: 'Top 10 Tracks'
  });

See the docs on React Context

Related