Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
Evertt opened this issue Mar 16, 2021 · 1 comment
Closed

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

Evertt opened this issue Mar 16, 2021 · 1 comment

Comments

@Evertt
Copy link

Evertt commented Mar 16, 2021

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
Copy link
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants