Thinkster
React

Performing HTTP Requests with Custom Middleware

A real world example of how to properly perform AJAX calls against an API server using Redux middleware

Valeri Karpov Up to date (Feb '17) React

This tutorial is a part of the "Build a Real World App with React & Redux" tutorial series.

With React & Redux applications, there isn't a standard library included for making HTTP requests (aka Ajax requests) to servers. As such, you'll need to choose a library or polyfill if you plan on making HTTP requests in your application.

For this application, we decided to use superagent as it's well adopted & supported in the Javascript community. It also provides a robust API that allows you to customize requests however you see fit.

First step, let's add an agent.js file that's going to use the superagent HTTP client library to make an HTTP request to the RealWorld API.

Create an agent.js file for our superagent requests
'use strict';

import superagentPromise from 'superagent-promise';
import _superagent from 'superagent';

const superagent = superagentPromise(_superagent, global.Promise);

const API_ROOT = 'https://conduit.productionready.io/api';

const responseBody = res => res.body;

const requests = {
  get: url =>
    superagent.get(`${API_ROOT}${url}`).then(responseBody)
};

const Articles = {
  all: page =>
    requests.get(`/articles?limit=10`)
};

export default {
  Articles
};

All you need to do now is get the value that the agent.Articles.all() promise resolves to into redux. Let's call this function when the Home component loads.