ConsoleTVs / sswr

🔥 Svelte stale while revalidate (SWR) data fetching strategy
MIT License
234 stars 11 forks source link

How does one declare the type of the incoming data? #5

Closed Evertt closed 3 years ago

Evertt commented 3 years ago

When I write this:

<script>
  import { useSWR } from "sswr"

  const { data: posts } = useSWR("https://jsonplaceholder.typicode.com/posts")
</script>

<ul>
  {#each $posts as post}
    <li>{post.title}</li>
  {/each}
</ul>

Then typescript tells me that I can't use $posts in an {#each} block, because the type of $posts is unknown.

edit

Okay I figured it out, apparently I needed to write it like so:

<script>
  import Counter from "$components/Counter.svelte"
  import { createSWR } from "sswr"

  interface Post {
    id: number
    userId: number
    title: string
    body: string
  }

  const swr = createSWR<Post[]>()

  const { data: posts } = swr.useSWR("https://jsonplaceholder.typicode.com/posts")
</script>

<ul>
  {#each $posts as post}
    <li>{post.title}</li>
  {/each}
</ul>

But is there a good reason why this has to go through createSWR? Why can't I define a type directly on the useSWR() function? Like const { data: posts } = useSWR<Post[]>("https://jsonplaceholder.typicode.com/posts") ?

ConsoleTVs commented 3 years ago

Was an issue. This worked if you created your own instance, but failed with the default one. Should now work as you described!