bier hier bier hier - 1 month ago 19
Javascript Question

How to setState to new data in react?

I just started looking at reactjs and trying to retrieve data through an api:

constructor(){
super();
this.state = {data: false}
this.nextProps ={};

axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
nextProps= response;
});
}


When the promise comes back I want to assign the data to the state:

componentWillReceiveProps(nextProps){
this.setState({data: nextProps})
}


How can I set the new state with the data received from the api? At the moment the state is not set?

jsbin ref:https://jsbin.com/tizalu/edit?js,console,output

Answer

The convention is to make an AJAX call in the componentDidMount lifecycle method. Have a look at the React docs: https://facebook.github.io/react/tips/initial-ajax.html

Load Initial Data via AJAX
Fetch data in componentDidMount. When the response arrives, store the data in state, triggering a render to update your UI.

Your code would therefore become: https://jsbin.com/cijafi/edit?html,js,output

class App extends React.Component {
  constructor() {
    super();
    this.state = {data: false}
  }

  componentDidMount() {
    axios.get('https://jsonplaceholder.typicode.com/posts')
        .then(response => {
            this.setState({data: response.data[0].title})
        });
  }

  render() {
    return (
     <div> 
      {this.state.data}
     </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

Here is another demo (http://codepen.io/PiotrBerebecki/pen/dpVXyb) showing two ways of achieving this using 1) jQuery and 2) Axios libraries.

Full code:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      time1: '',
      time2: ''
    };
  }

  componentDidMount() {
    axios.get(this.props.url)
      .then(response => {
        this.setState({time1: response.data.time});
      })
      .catch(function (error) {
        console.log(error);
      });

    $.get(this.props.url)
      .then(result => {
        this.setState({time2: result.time});
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <div>
        <p>Time via axios: {this.state.time1}</p>
        <p>Time via jquery: {this.state.time2}</p>
      </div>
    );
  }
};


ReactDOM.render(
  <App url={"http://date.jsontest.com/"} />,  document.getElementById('content')
);
Comments