Skip to content
On this page

How not to use Fetch API

Since Fetch API is supported in any modern browser and current version of Node.js Farfetched uses it to make HTTP calls. It adds zero overhead to client bundle and pretty fast on server side. However, in some cases you may want to switch to XMLHttpRequest or some wrappers about it (e.g. axios). Let us see how it can be done.

No Fetch in Query

You can use createQuery-factory and passes your handler to it 👇

ts
import { createQuery } from '@farfetched/core';
import axios from 'axios';

const usersQuery = createQuery({
  async handler() {
    const response = await axios.get('/users');

    return response.data;
  },
});

That is it, usersQuery is a regular Query that can be used in any function from Farfetched. Of course, you can use any other library to make HTTP calls the same way.

Furthermore, you can consider creating a custom Query factory to simplify Query creation across the application.

No Fetch in Mutation

TIP

Farfetched is build over concept re-using, so replacing Fetch API with other HTTP client in Mutation is a similar to Query case.

You can use createMutation-factory and passes your handler to it 👇

ts
import { createMutation } from '@farfetched/core';
import axios from 'axios';

const loginMutation = createMutation({
  async handler({ login, password }) {
    const response = await axios.post('/login', { login, password });

    return response.data;
  },
});

That is it, loginMutation is a regular Mutation that can be used in any function from Farfetched. Of course, you can use any other library to make HTTP calls the same way.

Furthermore, you can consider creating a custom Mutation factory to simplify Mutation creation across the application.

Cancellation support

Since we took control over HTTP calls from Farfetched, we need to take care about cancellation by ourselves. Fortunately, it is not hard to do. Let us see how it can be done.

Farfetched provides onAbort-function that allows to bind a passed function to the aborting of the Query or Mutation. Let us use it to abort axios-based Query 👇

ts
import { createQuery, onAbort } from '@farfetched/core';
import axios from 'axios';

const usersQuery = createQuery({
  async handler() {
    const controller = new AbortController(); 
    onAbort(() => controller.abort()); 

    const response = await axios.get('/users', {
      signal: controller.signal, 
    });

    return response.data;
  },
});

That is it, usersQuery supports cancellation now and operators like timeout will perform cancellation correctly.

You can use the same approach to add cancellation support to Mutation.

Released under the MIT License.