How to use recoil effects_unstable for loading data from API.

How to use recoil effects_unstable for loading data from API.

·

2 min read

Welcome friends 👋, to this new blog post where you will learn how to use effects_unstable for fetching the data from an API.

For people who know Hindi:

In this blog, I will use this API — https://jsonplaceholder.typicode.com/todos

🤔Situation

Suppose I have a website for making todos where I want to load the todos from an API. So, how will I do it with recoil?

Moreover, your project manager gave you this project which uses Nextjs as its framework and has made these files before 👇

atoms/atoms.ts

import { atom } from "recoil";
import { todosSelector } from "../selectors/selectors";

export type Todo = {
  id: number;
  title: string;
  completed: boolean;
  userId: number;
};

export const todosAtom = atom<Todo[]>({
  key: "todos",
  default: [],
});

Index.ts file

import type { NextPage } from "next";
import React, { useEffect } from "react";
import { useRecoilState } from "recoil";
import { todosAtom } from "../atoms/atoms";
import Box from "../components/Box";

const Home: NextPage = () => {
  // This will give us ability to get and change the value of the input of the user.
  const [todos, setTodos] = useRecoilState(todosAtom);



  return (
    <div className="flex min-h-screen flex-col items-center justify-center py-2">
      {todos.map((todo, index) => (
        <div key={index}>
          <p>{todo.title}</p>
        </div>
      ))}


    </div>
  );
};

export default Home;

🥳Solution to load the data

we have two methods

Method 1️⃣— Effects_unstable


import { atom } from "recoil";
import { todosSelector } from "../selectors/selectors";

export type Todo = {
  id: number;
  title: string;
  completed: boolean;
  userId: number;
};

export const todosAtom = atom<Todo[]>({
  key: "todos",
  default: [],
  effects_UNSTABLE: [
  // we cannot use async in these functions. So we have used then.
    ({ setSelf }) => {
      fetch("https://jsonplaceholder.typicode.com/todos").then((res) => {
        res.json().then((todos) => setSelf(todos));
      });
    },
  ],
});

Method 2️⃣— Effects_unstable

import { atom, selector } from "recoil";
import { todosSelector } from "../selectors/selectors";

export type Todo = {
  id: number;
  title: string;
  completed: boolean;
  userId: number;
};

export const todosAtom = atom<Todo[]>({
  key: "todos",
  default: selector({
    key: "todosS",
    get: async ({ get }) => {
      const res = await fetch("https://jsonplaceholder.typicode.com/todos");
      const todos = await res.json();

      return todos;
    },
  }),
});

⚠️Concerns

If you are using frameworks like nextjs then you need to know something unique and that is that recoil loads the data by serverside rendering which makes the website load slow.

For any questions, feel free to ask here 👇 Join the Next Dev Discord Server!

Did you find this article valuable?

Support Next Dev by becoming a sponsor. Any amount is appreciated!