Leyksnal
Leyksnal

Reputation: 33

Swr API request return error data.map is not a function in reactjs

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>
      );
    }

Upvotes: 0

Views: 1313

Answers (2)

Kassio Gluten
Kassio Gluten

Reputation: 21

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

mutate([])

instead of

mutate()

Upvotes: 0

utsav mehrotra
utsav mehrotra

Reputation: 11

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>
);
}

Upvotes: 1

Related Questions