0

Currently I have this code from my AppContext.js file

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

export const AppContext = createContext();

export class AppProvider extends Component {

state = {
    test: '',
};

getEntries() {
    console.log('FIRED');

    this.setState({test: 'HELLO'});
}

render() {
    return (
      <AppContext.Provider
          value={{
              ...this.state,
              getEntries: this.getEntries
          }}
      >
          {this.props.children}
      </AppContext.Provider>
    );
}

}

I'm calling the getEntries function and its displaying message from the console successfully but the this.setState is not working it says TypeError: this.setState is not a function

2 Answers2

0

The problem here is this is not bound to the right context.

The simplest workaround is probably to use this syntax:

getEntries = () => {
    ...
}

There are several ways in React to bind this to the class context: check this article for other ways.

Simone
  • 20,302
  • 14
  • 79
  • 103
0

getEntries function needs to be bind to the component. The simple way to do it is to use arrow function as shown below.

getEntries = () => {
    console.log('FIRED');

    this.setState({test: 'HELLO'});
}

The second way to bind getEnteries method to the component is

constructor(props) {
    super(props);
    // This binding is necessary to make `this` work in the callback
    this.getEntries = this.getEntries.bind(this);
  }
kemz
  • 99
  • 2
  • 9