Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Make Multiple SWR Data Fetch Calls In The Same React Component

This code let's you use multiple swr calls in the same component. The key is to apply a name to each one.

Code

const fetcher = (url) => fetch(url).then((res) => res.json())
 
const { data: playlists, error: playlistsError } = useSWR('/api/the-playlists', fetcher)
const { data: songs, error: songsError } = useSWR('/api/the-songs', fetcher)

Then you can check for each with:

Code

if (playlistsError) return <div>Could not get playlists</div>
if (!playlists) return <div>Loading playlists...</div>
// do something with playlists


if (songsError) return <div>Could not get songs</div>
if (!songs) return <div>Loading songs...</div>
// do something with songs

Messing with that is left as an exercise for the reader

Note that the useSWR can't go inside a basic function inside a component