Fetching Data with Jotai

Learn how to create asynchronous Jotai atoms for server data fetching, exploring read-only, write-only, and read-write atom concepts with practical examples.

Fetching real-time data

We successfully set up mocked image data in our app, but we would like to fetch real data from the server. Going back to the Jotai docs, we will find a guide on asynchronous atoms. Here’s what our async atom for fetching images will look like:

Press + to interact
// src/atoms/fetchImagesAtom.js
import { requestBase } from "../utils/constants";
import { atom } from "jotai";
// Atom for storing the list of images
export const imageListAtom = atom([]);
// Atom for the URL to fetch liked images
const urlAtom = atom(requestBase + "/john_doe/likedImages.json");
// Atom for fetching images asynchronously
export const fetchImagesAtom = atom(async (get) => {
// Fetch images from the specified URL
const response = await fetch(get(urlAtom));
// Return the parsed JSON data
return await response.json();
});

Let's look at the details of the code:

  • Line 2: We add a requestBase import to use URLs more comfortably.

  • Line 9: Then, we proceed to create a basic atom urlAto with the specific URL.

  • Lines 12–16: We can see that the last function is the async atom. We know it’s async because it uses the async keyword. The body of the async atom function is a fetch function and data return. ...