Z
Z
zwezew2019-03-06 14:02:31
JavaScript
zwezew, 2019-03-06 14:02:31

How to trigger re-render after changing json via fetch?

If the code renders the list from json using the fetch call in componentDidMount(), then how to trigger a re-render after any json modification via post, put, etc.?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavlo Ponomarenko, 2019-03-06
@zwezew

When the data that you request with fetch has arrived, put it in the state, and render from the state. Something like this:

class MyComponent extends React.Component {
  state = {
    loading: true,
    data: null
  }

 componentDidMount () {
    const data = await fetch(/* ... */);
    this.setState({ loading: false, data });
 }

 render () {
   const { data, loading } = this.state;

   if (loading) {
     return <div className='loading' />
   }

   return this.renderData(data);
 }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question