DEV Community

Konrad Lisiczyński
Konrad Lisiczyński

Posted on • Updated on

Taming network with redux-requests, part 9 - External libraries and promises

In the previous part of this series we discussed mocking and how to use multiple drivers at the same time within one app.

In this part we will cover how to integrate redux-requests with external libraries or if you would like to use it with promises directly.

External API libraries

Sometimes, as a front-end developer you will just get a ready to use library which handles connection with server. Then, you won't be able to use axios or fetch API driver, you need something else. If the library you received is promised based, which is usually the case, then you could use promise driver.

Using promise driver

To install it, just run:

npm install @redux-requests/promise

Then, as for any driver, you must pass it to handleRequests:

import { createDriver } from '@redux-requests/promise';

handleRequests({
  driver: createDriver({
    AbortController: window.AbortController,
    processResponse: response =>  ({ data: response }),
  }),
});

AbortController is optional, by default it will use AbortController if available, with fallback to DummyAbortController which does nothing. If your environment doesn't support AbortController, you could pass a polyfill.
If you don't, requests aborts won't work (but the app will still work, you will just lose the possibility to use automatic aborts feature).

processResponse is also optional, the default is response => ({ data: response }), it is useful if your promises resolve to more things than data, then you could for instance use response => ({ data: response.data }), or even response => ({ data: response.data, headers: response.headers })

Once you have done that, you can use promises in request actions:

const fetchPhoto = id => ({
  type: FETCH_PHOTO,
  request: {
    promise: axios.get(`/photos/${id}`),
  },
});

Also note, that just like for mock driver, for mutations you need to pass meta.asMutation: true in your request actions, so the core library could know whether a request is a query or a mutation. For many drivers like axios, fetch and graphql it is not usually necessary as the library can deduct whether something is a query or a mutation by looking at request config, like GET request method will be typically a query while POST a mutation.

What's next?

In the next part we will discuss server side rendering, SSR in short and how redux-requests can help you writing truly universal code between client and server.

Top comments (0)