DEV Community

Ramu Narasinga
Ramu Narasinga

Posted on • Edited on • Originally published at thinkthroo.com

1 1 1

useSWR usage in vercel/ai-chatbot hooks.

In this article, we will review the useSWR usage in vercel/ai-chatbot source code. I found two examples in hooks folder where useSWR is used. 

  1. vercel/ai-chatbot/hooks/use-artifact.ts#L3

  2. vercel/ai-chatbot/hooks/use-chat-visibility.ts#L4

Image description

use-artifact.ts

Let’s begin with use-artifact.ts. You will find the below import at L#3

import useSWR from 'swr';
Enter fullscreen mode Exit fullscreen mode

L25–27 contain the below code

const { data: localArtifact } = useSWR<UIArtifact>('artifact', null, {
    fallbackData: initialArtifactData,
});
Enter fullscreen mode Exit fullscreen mode

At this point, I would go read the useSWR documentation because, well, I forgot the definition.

SWR

The name “SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861(opens in a new tab). SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.

With SWR, components will get a stream of data updates constantly and automatically.

And the UI will be always fast and reactive.

Following is overview picked from SWR site.

import useSWR from 'swr'

function Profile() {
  const { data, error, isLoading } = useSWR('/api/user', fetcher)

  if (error) return <div>failed to load</div>
  if (isLoading) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}
Enter fullscreen mode Exit fullscreen mode

In this example, the useSWR hook accepts a key string and a fetcher function. key is a unique identifier of the data (normally the API URL) and will be passed to fetcher. fetcher can be any asynchronous function which returns the data, you can use the native fetch or tools like Axios.

The hook returns 3 values: data, isLoading and error, based on the status of the request.

Read more about SWR.

Now that we understand the basics of SWR, let’s get back to the example.

const { data: localArtifact } = useSWR<UIArtifact>('artifact', null, {
    fallbackData: initialArtifactData,
});
Enter fullscreen mode Exit fullscreen mode

Looks like there is no fetcher defined in this usecase as there is null and there is a fallbackData which is initialArtifactData that is defined at the top of this hook.

export const initialArtifactData: UIArtifact = {
  documentId: 'init',
  content: '',
  kind: 'text',
  title: '',
  status: 'idle',
  isVisible: false,
  boundingBox: {
    top: 0,
    left: 0,
    width: 0,
    height: 0,
  },
};
Enter fullscreen mode Exit fullscreen mode

Following are the other usecases where useSWR is used

 const { data: localArtifact, mutate: setLocalArtifact } = useSWR<UIArtifact>(
    'artifact',
    null,
    {
      fallbackData: initialArtifactData,
    },
  );

const { data: localArtifactMetadata, mutate: setLocalArtifactMetadata } =
    useSWR<any>(
      () =>
        artifact.documentId ? `artifact-metadata-${artifact.documentId}` : null,
      null,
      {
        fallbackData: null,
      },
    );
Enter fullscreen mode Exit fullscreen mode

So there’s no fetcher altogether in this use-artifact hook. Interesting…

use-chat-visibility.ts

In this use-chat-visibility.ts, useSWR is found to be used only once as shown below:

 const { data: localVisibility, mutate: setLocalVisibility } = useSWR(
    `${chatId}-visibility`,
    null,
    {
      fallbackData: initialVisibility,
    },
  );
Enter fullscreen mode Exit fullscreen mode

Again, there is no fetched in this hook too, there is a fallbackData.

About me:

Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.

I am open to work on interesting projects. Send me an email at ramu.narasinga@gmail.com

My Github —  https://github.com/ramu-narasinga

My website —  https://ramunarasinga.com

My Youtube channel —  https://www.youtube.com/@ramu-narasinga

Learning platform —  https://thinkthroo.com

Codebase Architecture —  https://app.thinkthroo.com/architecture

Best practices —  https://app.thinkthroo.com/best-practices

Production-grade projects —  https://app.thinkthroo.com/production-grade-projects

References:

  1. https://github.com/vercel/ai-chatbot/blob/main/hooks/use-artifact.ts#L3

  2. https://github.com/vercel/ai-chatbot/blob/main/hooks/use-chat-visibility.ts#L4

  3. https://swr.vercel.app/

AWS Security LIVE! Stream

Streaming live from AWS re:Inforce

Tune into Security LIVE! at re:Inforce for expert takes on modern security challenges.

Learn More

Top comments (2)

Collapse
 
nevodavid profile image
Nevo David

Wow they used useSWR with no fetcher just as a local store pretty much like stashing snacks in your desk for later what risks come with skipping the real fetch call and leaning just on fallback data like that

Collapse
 
ramunarasinga-11 profile image
Ramu Narasinga

Yeah, was amazed when I found that. Quite interesting pattern.

AWS Security LIVE! Stream

Streaming live from AWS re:Inforce

What’s next in cybersecurity? Find out live from re:Inforce on Security LIVE!

Learn More