0

I'm trying to write a recursive function inside a React component but when I call it I get the error:

TypeError: this.loadFromStorage is not a function

This is my code:

class Availability extends Component {
    state = { availability: [] }
    componentDidMount() {
      this.getAvailability();
    }

    loadFromStorage = () => {
      let data = sessionStorage.getItem(this.props.manufacturer);
      if(data) {
        let availability = JSON.parse(data);
        this.setState({availability});
      } else {
        setTimeout(function() { this.loadFromStorage(); }, 200);
      }
    }

    getAvailability = () => {
    // calls this.loadFromStorage()
...
General Gravicius
  • 181
  • 1
  • 2
  • 10

1 Answers1

1

It seems the issue is, that you are not using arrow functions for callbacks

        setTimeout(function() { this.loadFromStorage(); }, 200);

should be

        setTimeout(() => this.loadFromStorage(), 200);

as anonymous function has always global (window) as this by default. While arrow functions always uses this from place of declaration (So it would be your component in the case), same for loadFromStorage itself, which is arrow function, internally it runs inside constructor, before actual constructor code.

SergeS
  • 11,533
  • 3
  • 29
  • 35