-1

I run successfully the following code from SWR examples page:

import useSWR from "swr";

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

export default function App() {
  const { data, error } = useSWR(
    "https://api.github.com/repos/vercel/swr",
    fetcher
  );

  if (error) return "An error has occurred.";
  if (!data) return "Loading...";
  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.description}</p>
      <strong>{data.subscribers_count}</strong>{" "}
      <strong>{data.stargazers_count}</strong>{" "}
      <strong>{data.forks_count}</strong>
    </div>
  );
}

However when I use my custom API and update the properties to be rendered ({data.id}, {data.title}...), I get "An error has occurred".

If I remove conditional returns I get "data is undefined":

Unhandled Runtime Error TypeError: data is undefined

I've used my API in other parts of the project and have had no issues.

Luis García
  • 43
  • 1
  • 5
  • what does actual error says? – Nonik Oct 27 '20 at 23:12
  • @Nonik "Unhandled Runtime Error. TypeError: data is undefined" – Luis García Oct 27 '20 at 23:21
  • Temporarily modify your last `return` to something simple like `
    `, then set a breakpoint or console.log(data) before the `return` to see what's inside the data.
    – nghiaht Oct 28 '20 at 06:30
  • @nghiaht Console shows an error regarding CORS header: "Reason: CORS header 'Access-Control-Allow-Origin' missing". I guess it should be added in the backend – Luis García Oct 28 '20 at 22:37
  • But the backend is "https://api.github.com/repos/vercel/swr", it seems weird – nghiaht Oct 29 '20 at 02:41
  • @nghiaht I have no issues fetching the github API. It's only my custom API that is causing trouble – Luis García Oct 29 '20 at 03:26
  • That means the `"https://api.github.com/repos/vercel/swr"` is an example, you are using `/api/custom...` in your code? – nghiaht Oct 29 '20 at 06:12
  • If you use Next.js's API routes, maybe you have to add CORS, check out this https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors – nghiaht Oct 29 '20 at 06:21

1 Answers1

0

I personally handle it like this example

useRequest.js:

import useSWR from 'swr'
import axios from 'axios'

export default function useRequest(request, { initialData, ...config } = {}) {
  return useSWR(
    request && JSON.stringify(request),
    () => axios(request || {}).then(response => response.data),
    {
      ...config,
      initialData: initialData && {
        status: 200,
        statusText: 'InitialData',
        headers: {},
        data: initialData
      }
    }
  )
}

sample.jsx:

  import useRequest from '../libs/useRequest'

  const { data } = useRequest({
    url: 'https://api.github.com/repos/vercel/swr'
  })
Reza Babaei
  • 905
  • 1
  • 14
  • 22