0

When I try to access a state variable which is set in ComponentDidMount, react throws an undefined error. This is because I believe when I'm calling the fetch api and setState in ComponentDidMount, the value isn't ready yet (async stuff). Is there a proper way to either delay the render until the setState call is done or some other way to get the state updated fully before render is called?

GianhTran
  • 3,443
  • 2
  • 22
  • 42
  • 4
    You can (and should) show some loading UI until the fetch finishes. Just have the data in state with an initial value. Then when that initial value changes, switch to rendering from the fetched data – Andrew Li Sep 17 '18 at 00:29
  • 5
    Thinking about this wrong. See https://reactjs.org/docs/conditional-rendering.html – charlietfl Sep 17 '18 at 00:36
  • Possible duplicate of [Is setState() inside componentDidMount() considered an anti-pattern](https://stackoverflow.com/questions/52168047/is-setstate-inside-componentdidmount-considered-an-anti-pattern) – Buggy Sep 17 '18 at 06:14

1 Answers1

1

I think the code below will give you a basic idea how fetch data and render work.

class App extends Component {
    state = { 
        data:{},
        loading:true,
        error:null,
     }
     componentDidMount = () => {
        fetch('https://example.com/api/article')
        .then((response) => {
          return response.json();
        })
        .then((json) => {
          this.setState({
            data:json,
            loading:false,    
          }) 
          .catch(error => {
            this.setState({
                error,
                loading:false,
              })  
          });
        });

     }

    render() {
        const {data,error,loading} = this.state;
        if(loading){
            return "Loading ..."
        }
        if(error){
            return "Something went wrong."
        }
        return 'your actual render component or data';
    }
}

export default App;
Kyaw Kyaw Soe
  • 3,258
  • 1
  • 14
  • 25