SWR data fetching returning same results for different components

22 Views Asked by At

I have a nextjs app that fetches data from Wordpress wpgraphql plugin. At first I used native fetch to get the data and it was giving me data properly. Then i decided to use SWR. Problem is that I have a 6 different categories that have to be displayed in my front page, but I get result of only one category in every component. Its like it is reflecting the results from one component in every other one , no matter if I change the category name which is a second param in fetcher function

    "use client";
    import useWindowSize from "@/app/lib/useWindowSize";
    import Link from "next/link";
    import nasStyles from "../../../css/naslovnicaCss/     naslovnica.module.css";
    import LifestyleNaslovnaDetails from "./LifestyleNaslovnaDetails";
    import { fetcher, temporaryApiUrl } from "@/app/lib/fetchDb";
    import useSWR from "swr";

    const LifestyleNaslovna = () => {
    const isMobile = useWindowSize();
    const useClientApi = () => {
    const apiUrl = temporaryApiUrl;

   const { data, error, isValidating } = useSWR(
     isMobile ? null : apiUrl,
     (url) => fetcher(url, "Lifestyle", 1)
    );

    if (error) {
      console.error("SWR Error:", error);
     }

    return {
    data,
    error,
    isLoading: !data && !error,
    isFetching: isValidating,
     };
    };
   const { data, error, isLoading, isFetching } = useClientApi();

   if (isMobile) {
    return null;
   }
   if (isMobile === undefined) {
     return null;
   }

   if (isLoading) {
     return <h1>Loading....</h1>;
   }

    return (
   <div>
    <h3 className={nasStyles.naslovnicaHeading}>
    <Link href={`/category/lifestyle`}>LIFESTYLE</Link>
    </h3>
     <div className={nasStyles.grid3GrudeOnline}>
     {data.map((item: any, index: number) => {
      return <LifestyleNaslovnaDetails key={index} data={item} />;
    })}
  </div>
  </div>
  );
 };

  export default LifestyleNaslovna;

When I pass a string to a fetcher function In different component for example SportNaslovna component fetcher(apiUrl,"Sport",3) i still recive a results from a fetcher from LifestyleNaslovna component and don`t understand why is it happening.

Here is a fetcher function :

     export const fetcher = async (
     url: any,
     category: string,
     numOfPosts: number
     ) => {
      try {
        const response = await fetch(url, {
        method: "POST",
        headers: {
        "Content-Type": "application/json",
        },
       body: JSON.stringify({
       query: `query NewQuery {
           posts(first: ${numOfPosts}, where: {categoryName: "${category}"}) {     
            nodes {
            slug
            title
            content
            date
            postId
            featuredImage {
             node {
               sourceUrl(size: LARGE)
             }
           }
           categories {
             edges {
              node {
                slug
              }
            }
          }
          tags {
            nodes {
              name
             }
           }
          }
        }
      }`,
      }),
     });

     if (!response.ok) {
      throw new Error("Network response was not ok");
     }

      const result = await response.json();
      return result?.data?.posts?.nodes;
     } catch (error) {
        console.error("Error fetching data:", error);
     throw error; // Re-throw the error so that useSWR can handle it
     }
    };
0

There are 0 best solutions below