React

Performing HTTP Requests with Custom Middleware

PRO
Outline

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 (a.k.a. Ajax requests). 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.

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. This file will contain our constants and helper functions.

Create an agent.js file for our superagent requests

src/agent.js

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
};

Now we need to get the value that agent.Articles.all() promise resolves to into redux.

 

I finished! On to the next chapter