Loading

30 Hours React JS Course - #16

Tarun Sharma

This is a live streamed presentation. You will automatically follow the presenter and see the slide they're currently on.

30 Hours Course React #15 ​

fetching data API

React simply renders components, using data from only two places: props and state.

 

 

So therefore, to use some data from the server, you need to get that data into your components’ props or state.

HTTP Library

Text

Choose an HTTP Library

To fetch that data from the server, you’ll need an HTTP library. There are a ton of them out there. Ultimately they all do the same thing, but they have different features.

Like promises? Go with axios.

 

Hate promises, but love callbacks? Take a look at superagent.

Rather use something soon-to-be-standardized? fetch might be your favorite.

 

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

class FetchDemo extends React.Component {
  state = {
    posts: []
  }

  componentDidMount() {
    axios.get(`http://www.reddit.com/r/${this.props.subreddit}.json`)
      .then(res => {
        const posts = res.data.data.children.map(obj => obj.data);
        this.setState({ posts });
      });
  }

  render() {
    return (
      <div>
        <h1>{`/r/${this.props.subreddit}`}</h1>
        <ul>
          {this.state.posts.map(post =>
            <li key={post.id}>{post.title}</li>
          )}
        </ul>
      </div>
    );
  }
}

axios

componentDidMount

componentDidMount is where the magic happens.

 

This method will be executed when the component “mounts” (is added to the DOM) for the first time. This method is only executed  once during the component’s life.

 

 

Fetch server data in the componentDidMount lifecycle method

Fetch

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

Where in the component lifecycle should I make an AJAX call?

 

You should populate data with AJAX calls in the componentDidMount lifecycle method. This is so you can use setState to update your component when the data is retrieved.

Thanks..

Made with Slides.com