Ajax in React

Today I will share you the example that how ajax call can be done in react. You can choose any HTTP library but i will choose the axios. Here is the example this code will take reddit aww subreddit text and images from subreddt aww(cute pictures of animals). Here is the following code
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

class AjaxDemo extends React.Component {
    constructor(props) {
        super(props);

        this.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 });
                console.log(posts);
            });
    }

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

ReactDOM.render(
    <AjaxDemo subreddit="aww"/>,
    document.getElementById('root')
);
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.

Share this post