Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setState to new data in react?

I just started looking at reactjs and trying to retrieve data from an API:

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

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

When the promise returns the data, I want to assign it to the state:

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

How can I update the 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

like image 880
bier hier Avatar asked Oct 05 '16 06:10

bier hier


1 Answers

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')
);
like image 161
Piotr Berebecki Avatar answered Sep 19 '22 20:09

Piotr Berebecki