1

I try to display data and I use swr data fetching with react and here is the code :

import useSWR from "swr";
import axios from "axios";
const fetcherFunc = (...args) => {
  return axios(...args).then((res) => console.log(res.data));
};
function MyComponent() {
  const { data, error } = useSWR(
    "https://jsonplaceholder.typicode.com/posts/",
    fetcherFunc
  );
  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;
  return <div>{JSON.stringify(data)}</div>;
}
export default MyComponent;

The problem is that it's stuck in loading and the data won't get updated and is undefined also the console log of data in fetcher appears to work .

How to fetch data with swr in react and display fetched data ?

1 Answer 1

3

You're supposed to return res.data from fetcherFunc instead of console.log-ing data.

Also, just use url as the name of the argument for the fetcherFunc and pass that url to axios.get (don't use ...url spread operator on url). Take look at How To Use Axios for Data Fetching (passing the url, method, payload, etc).

Function for fetching the data should look like:

const fetcherFunc = (url) => axios.get(url).then((res) => res.data);

As for the useSWR hook, use it like this:

const { data, error } = useSWR("https://jsonplaceholder.typicode.com/posts/", fetcherFunc);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.