N
N
Nick Fisher2019-02-21 15:43:06
React
Nick Fisher, 2019-02-21 15:43:06

Where to call fetch?

Good afternoon. I have a table with data and a checkbox. By default, it is in the new position and pulls data from the back according to the corresponding fetch (data from which is written to the state) and other data in the all position. The question is where exactly should I make the initial call. If in the render (which is obviously bad, then it will call the method 2 times, because after the setstate it will go into the render again), if in the did mount component, then the call will be only 1 (it is not possible to call it forcibly, the fetch should occur depending on checkbox). Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Spirin, 2019-05-01
@Nick Fisher

class Example extends React.Component {
  state = { filter: 'all' };

  componentDidMount() {
    this.props.fetchData(this.state.filter);
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.filter !== this.state.filter) {
       this.props.fetchData(this.state.filter);
    }
  }
  
  render() { /* ... */ }
}

A
Andrey Okhotnikov, 2019-02-21
@tsepen

The first fetch in didMount, all subsequent fetches on the onChange event on the checkbox.
If you call it in the render, it will be called endlessly and this will all end)

D
davidnum95, 2019-02-21
@davidnum95

Author, don't worry https://codesandbox.io/s/821z9l0ym8

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question