Skip to content
On this page

Step 1: Wrap existing data fetching Effects

TIP

In this tutorial, we assume you have an application that uses Effects for data fetching.

Farfetched has two primitives for data fetching: Queries and Mutations. It is a complete replacement for Effects used for data fetching. Let's start with a key difference between Effects and Queries/Mutations.

Effects vs Queries/Mutations

Differences between Queries and Mutations

Wrap Effects to Queries and Mutations

All Farfetched APIs are designed to be used with Queries and Mutations. So, to take advantage of Farfetched, we need to wrap existing Effects to Queries and Mutations.

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

const fetchUserFx = createEffect(/*...*/);
const userQuery = createQuery({ effect }); 

const createPostFx = createEffect(/*...*/);
const createPostMutation = createMutation({ effect }); 

After this change, instead of direct usage of Effects we have to use Queries and Mutations.

ts
// Use .start Event instead of Effect
sample({
  clock: someTrigger,
  target: fetchUserFx, 
  target: userQuery.start, 
});

// Use .finished.success Event instead of .done Event
sample({
  clock: fetchUserFx.done, 
  clock: userQuery.finished.success, 
  target: someTarget,
});

// Use .finished.failure Event instead of .fail Event
sample({
  clock: fetchUserFx.fail, 
  clock: userQuery.finished.failure, 
  target: someTarget,
});

// Use .$data Store instead of creating a new Store
const $user = createStore(null); 
$user.on(fetchUserFx.doneData, (_, newUser) => newUser); 
const $user = userQuery.$data; 

As soon as no code in the application uses Effects directly, we can hide them to prevent accidental usage.

ts
const fetchUserFx = createEffect(/*...*/); 
const userQuery = createQuery({ effect }); 

const userQuery = createQuery({ effect: createEffect(/*...*/) }); 

This simple step allows us to use Farfetched APIs with existing Effects without rewriting big parts of the codebase. For example, now we can easily add retries to userQuery:

ts
import { retry } from '@farfetched/core';

retry(userQuery, { limit: 3, delay: 1000 });

We will dive into more details about Farfetched APIs in the next steps of this tutorial.

Released under the MIT License.