0

i am trying to consume from an API using useSWR() libary and the data to be return is an array of objects so i decided to try the axios method at first to make the request by doing below

    const fetcher = (url) => axios.get(url).then((resp) => resp.json());

But this fetcher didnt work so i tried using the fetch method and i noticed the data was retrieved but i tried mapping, it was giving me an arror that says data.map is not a funtion.

    const fetcher = (...args) => fetch(...args).then((resp) => resp.json());

    function Swr() {
    const { data, error } = useSWR(
        "https://callcaree.herokuapp.com/api/member",
        fetcher,
        { suspense: true }
       );

      //the data
      console.log(data);

      if (error) {
        return <h1> There was an error!</h1>;
      }

      return (
        <div>
          {data?.map((props) => {
            <div key={props._id}>
              <h3>{props.title}</h3>
           </div>;
          })}
        </div>
      );
    }
juliomalves
  • 42,130
  • 20
  • 150
  • 146
Leyksnal
  • 13
  • 5

2 Answers2

1

This is showing error because the data you are using to map is not array its object you have data inside data and another data inside that data you have to use that data to map i have written the code in sandbox so that you can understand it better

import axios from "axios";
import useSWR from "swr";

export default function App() {
const fetcher = (url) => axios.get(url).then((resp) => resp);

const { data, error } = useSWR(
"https://callcaree.herokuapp.com/api/member",
  fetcher,
  {
    suspense: true
  }
);
if (error) {
  return <h1> There was an error!</h1>;
}

return (
  <div>
    {data.data.data.map((props) => {
      return (
        <div key={props._id}>
          <h3>{props.name}</h3>
        </div>
      );
    })}
  </div>
);
}
  • Big Thanks to you i was able to figure out where the error was coming from with the help of your code. please take a look at this question here https://stackoverflow.com/q/73175550/16313700 – Leyksnal Jul 30 '22 at 12:18
0

i was having a similar problem after mutating it, fixed by calling

mutate([])

instead of

mutate()