Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set initial React state from API data?

Tags:

I have a rest API back end set up. I want to set values inside the getInitialState function for a component, but I can't figure out how to populate the object I need to return because I am using an asynchronous http request. The object I return has undefined values, as expected. How do I get around this?

I'm using fetch (can switch to any other library, honestly) as of now. I can't figure out how to call getInitialState after the asynchronous call has returned some value instead of before it happens.

import React from 'react';
import 'whatwg-fetch';

export default class IndexPage extends React.Component {

  render() {

    // I basically need to call getInitialState after the last promise has been resolved
    fetch('https://localhost:3000/api/aye')
    .then(function(response) {
      return response.json();
    })
    .then(function(json) {
      // Need to return some values from this.
    });

    return (
      <div>
        <h1>{this.state.jsonReturnedValue}</h1>
      </div>
    );
  }
}

Thanks in advance!

like image 902
Zeokav Avatar asked Dec 19 '16 13:12

Zeokav


People also ask

How do you set state after API call in React?

To set initial React state from API data, we can make the request in the useEffect callback. And we pass in an empty array as the 2nd argument to only make it run when the component mounts. We have the getAns function that makes a GET request with fetch . Then we call res.

How do you create an initial state in React?

There are two ways to initialize state in a React component: inside the constructor, and directly inside the class.

How do I assign a state in React?

To make the state change, React gives us a setState function that allows us to update the value of the state. Calling setState automatically re-renders the entire component and all its child components. We don't need to manually re-render as seen previously using the renderContent function.


2 Answers

You should call this.setState in order to change state values

export default class IndexPage extends React.Component {

  constructor() {
    super();
    
    this.state = {
      jsonReturnedValue: null
    }
  }
  
  componentDidMount() {
    fetch('https://localhost:3000/api/aye')
      .then(response => response.json())
      .then(json => {
        this.setState({ jsonReturnedValue: json });
      });
  }
  
  render() {
    return (
      <div>
        <h1>{ this.state.jsonReturnedValue }</h1>
      </div>
    );
  }
}
like image 96
Oleksandr T. Avatar answered Oct 13 '22 17:10

Oleksandr T.


In your situation -

It's better to get the rendering done for the first time with empty state data lets say

constructor(props){
    super(props);

    this.state = {
        data : []
    };
}

and make ajax call in componentDidMount, this is the place where you can perform dom manipulation and send ajax request to fetch data via REST.

After new data is fetched from server set the state with new data

this.setState({data:newDataFromServer});

e.g In componentDidMount

componentDidMount() {
 sendAjaxRequest()
 .then(
      (newDataFromServer) => {
              this.setState({data : newDataFromServer });

     });
}

This will cause the re-rendering to happen with latest data fetched from server and new state changes will be reflected.

like image 29
WitVault Avatar answered Oct 13 '22 18:10

WitVault