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.
We'll cover the following...
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:
// src/atoms/fetchImagesAtom.jsimport { requestBase } from "../utils/constants";import { atom } from "jotai";// Atom for storing the list of imagesexport const imageListAtom = atom([]);// Atom for the URL to fetch liked imagesconst urlAtom = atom(requestBase + "/john_doe/likedImages.json");// Atom for fetching images asynchronouslyexport const fetchImagesAtom = atom(async (get) => {// Fetch images from the specified URLconst response = await fetch(get(urlAtom));// Return the parsed JSON datareturn await response.json();});
Let's look at the details of the code:
Line 2: We add a
requestBaseimport to use URLs more comfortably.Line 9: Then, we proceed to create a basic atom
urlAtowith the specific URL.Lines 12–16: We can see that the last function is the
asyncatom. We know it’s async because it uses theasynckeyword. The body of theasyncatom function is afetchfunction and data return. ...