0

I'm trying to use useSWR in my NEXT.JS app. First, I made a custom hook where I use it :

import useSWR from "swr";

const apiUrl = process.env.NEXT_PUBLIC_API_URL;

const fetcher = (url) => {
  fetch(url).then((res) => res.json());
};

export default function useSocialMedia() {
  const url = apiUrl + "/socialMedia";
  const { data, error } = useSWR(url, fetcher);
  console.log("data : ", data);

  return {
    socialMedia: data,
    loading: !error && !data,
    error: error,
  };
}

Then, I import it in my component :

import styles from "./styles/socialIcons.module.scss";
import useSocialMedia from "../../../utils/hooks/useSocialMedia";

export default function SocialIcons() {
  const { socialMedia, loading, error } = useSocialMedia();

  return (
    <div className={styles.socialIcons}>
      {loading && <p>Loading...</p>}
      {error && <p>Loading failed : {error}</p>}
      {socialMedia && <p>Here will appear my social media list</p>}
    </div>
  );
}

As a result of my console.log in my custom hook, I always have data undefined and so my component is stuck with loading... I don't understand what's wrong with my code.

  • As far as I can see from your code, you are not returning any data in fetcher function. – Mithat Ercan Nov 08 '22 at 14:51
  • Sorry I pasted my code with console.log in my fetcher. I edited my question because even with the fecther returning data, it's still undefined after useSWR... – Fabien Delmotte Nov 08 '22 at 15:16

1 Answers1

2

Consider the following example. You forgot to return data in the fetcher function. You just used console.log and it returned no results.



import React from 'react';
import useSWR from 'swr';

const apiUrl = 'https://jsonplaceholder.typicode.com/posts';

const fetcher = (url) => fetch(url).then((r) => r.json());

function useSocialMedia() {
  const url = apiUrl;
  const { data, error } = useSWR(url, fetcher);

  return {
    socialMedia: data,
    loading: !data,
    error,
  };
}

export default function SocialIcons() {
  const { socialMedia, loading, error } = useSocialMedia();

  return (
    <div>
      {loading && <p>Loading...</p>}
      {error && <p>Loading failed : {error}</p>}
      {socialMedia && socialMedia.map((post) => <p>{post.title}</p>)}
    </div>
  );
}




Mithat Ercan
  • 403
  • 3
  • 13
  • Sorry I pasted my code with console.log in my fetcher. I edited my question because even with the fecther returning data, it's still undefined after useSWR... – Fabien Delmotte Nov 08 '22 at 15:15
  • Examine the fetcher function; it's enclosed in curly brackets; to return fetch, use the return keyword or delete the curly brackets. You may look at my code to see how I built the fetcher function. – Mithat Ercan Nov 08 '22 at 15:19
  • Thank you ! I just did a rookie mistake... I think it's time I take a coffee brake... It's now working like a charm ! – Fabien Delmotte Nov 08 '22 at 15:23