简体   繁体   中英

How can I set initial React state from API data?

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!

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> ); } }

You should do something along the following. Firstly, create the state in the constructor method. This will then allow you to use this value in your render method by referencing {this.state.jsonReturnedValue} . The constructor() method is the ES6 version of getInitialState() in case you are not aware of this. This is where you should set the state of the component.

Then in the componentDidMount which will run after the render method you can make the API call api and use React's setState method to update the value of this.state.jsonReturnedValue .

When this.setState() runs and sets a new value it will then run the render method again and update the view accordingly.

export default class IndexPage extends React.Component {

   constructor(){
     super();
     this.state = {
        jsonReturnedValue: null
     }
   }

  componentDidMount() {
    this.jsonList();
  }

  jsonList() {
     fetch('https://localhost:3000/api/aye')
    .then(function(response) {
      this.setState({
        jsonReturnedValue: response.json()
      }) 
    })
  }

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

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});

eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM