Next.js Discord

Discord Forum

SWR not caching / deduping requests?

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
Hi 👋 , I'm developing a dashboard application which has numerous pages making use of dynamic routes - see image below for page structure. Most of these I've just made client components for simplicity, and due to the high amount of interactivity and conditional rendering in my app, and due to my lack of experience with Next - to be honest I'm hoping to keep this as is right now.

However, users will move between pages frequently, and thus it'd be ineffective for me to make a request to my backend API server every time a user changes page, and thus I was looking for a way of sharing state across my client components - as all of the data needed by all dashboard pages is contained inside of one large 'org' object.

I then implemented SWR, as whilst this doesn't share the data, it claims to cache it so that data appears instantenously, whilst it queries new, updated data from the external API. However, this is not the case? When moving between http://localhost:3001/dashboard/7265315503164362752/groups and http://localhost:3001/dashboard/7265315503164362752, I am getting my 'loading state' for around a second - suggesting the cache isn't working?

Any suggestions?

Org Page:
'use client';

import useOrg from '@/utils/useOrg';
import axios from 'axios';
import { redirect, useParams } from 'next/navigation';
import { useState, useEffect } from 'react';

export default function Organisation({ params }: { params: Promise<{ org: string }> }) {
  const { org, isLoading, isError } = useOrg(useParams<{ org: string }>().org);

  return (
    <div className="">
      <h3>Organisation</h3>
      {isLoading ? <div>Loading...</div> : <div>{org?.name}</div>}
    </div>
  );
}

1 Reply

Giant pandaOP
Groups Page:
'use client';
import useOrg from '@/utils/useOrg';
import { useParams } from 'next/navigation';

export default function Groups({ params }: { params: Promise<{ org: string }> }) {
  const { org, isLoading, isError } = useOrg(useParams<{ org: string }>().org);

  return (
    <div className="">
      <h3>Groups</h3>
      {isLoading ? <div>Loading...</div> : <div>{org?.name}</div>}
    </div>
  );
}


'Use Org':
import useSWR from 'swr';

async function fetcher(orgId: string) {
  const data = fetch(`http://localhost:3000/api/orgs/${orgId}`, { credentials: 'include' }).then((res) => res.json());

  return data;
}
export default function useOrg(orgId: string) {
  const { data, error, isLoading } = useSWR('org', () => {
    return fetcher(orgId);
  });
  return { org: data, isLoading, isError: error };
}