1

I have a very simple query to an external API:

 const fetcher = (...args) => fetch(...args).then(x=>x.json())
 const {data:{results}, error} = useSWR("https://xxxxxxxxxxxxxxxx",fetcher)

Whenever I use it like this to destructure the data variable, I get an error saying that "results" is not defined. I can only access results as "data.results", is this a normal behavior?

Joe
  • 1,076
  • 3
  • 10
  • 17
  • What is the actual error message? – Konrad Apr 08 '23 at 22:22
  • TypeError: Cannot read properties of undefined (reading 'results') – Joe Apr 08 '23 at 22:28
  • The variable seems to take some time get the response back from the external API, because it does get it later if I conditionally render the variable and receive it as just "data" and not "data:{results}". – Joe Apr 08 '23 at 22:30
  • It's `data` which is `undefined` initially. You can't destructure `undefined` – Konrad Apr 08 '23 at 22:32
  • How can I wait for the result using SWR and store it in a variable? – Joe Apr 08 '23 at 22:46

1 Answers1

2

If data isn't resolved, then at build time you can't deconstruct like that. If you happen to use typescript, maybe it'll be more clear. Since I bet data has to have type whateverType | null. THe null prevents the deconstruction at the compile time.

In short, just use data. And then if (data.results) {} at the runtime then.

windmaomao
  • 7,120
  • 2
  • 32
  • 36
  • Yes. I was rendering the result with a condition in runtime, but I thought I could do the destructuring during build time. Oh well. I guess I have to settle for rendering conditionally during runtime as {data && data.results.map(res=>
    ...
    )}
    – Joe Apr 10 '23 at 01:07