#What is the correct type for this SWR variable?

7 messages · Page 1 of 1 (latest)

rapid whale
#

I'm trying to get the hang of SWR and Typescript with a simple JSX program:

export default function Home() {


  const fetcher : Fetcher<string , string> = async (...args) => await fetch(...args).then(r=>r.json())

  const {data} : Cat = useSWR("https://xxxxxxxxxxxxxxxxxxxxx", fetcher) //returns array of type Cat
  
  return <>{data && JSON.stringify(data)}</>
}

However, I'm getting turned around by {data} since it's giving me the error:

Type 'SWRResponse<string, any, any>' is missing the following properties from type 'Cat': id, url, width, heightts(2739)
Property 'data' does not exist on type 'Cat'.ts(2339)

This is what the type Cat is:

export interface Cat {
    id : string,
    url: string,
    width: number,
    height : number
}

I just want to use the type Cat on {data}, but I'm not quite sure how to do it in this simple example. What am I missing?

I'm also not super sure about the Fetcher function, I've included it to see if I need to change that as well.

#

!helper

thin vaultBOT
#

:warning: Please wait a bit longer. You can ping helpers <t:1689888864:R>.

dusk mural
#
import useSWR, { Fetcher } from 'swr'
 
const uid = '<user_id>'
const fetcher: Fetcher<User, string> = (id) => getUserById(id)
 
const { data } = useSWR(uid, fetcher)
// `data` will be `User | undefined`.
#

the type for your Fetcher is wrong

rapid whale
# dusk mural ```ts import useSWR, { Fetcher } from 'swr' const uid = '<user_id>' const fetc...

I was able to edit the code to:

  const fetcher : Fetcher<Cat , string> = async (...args) => await fetch(...args).then(r=>r.json())

  const {data} : SWRResponse = useSWR("https://xxxxxxxxxxxxxxxx", fetcher)

Somehow this managed to work, but what also worked was:

  const fetcher : Fetcher<Cat , string> = async (...args) => await fetch(...args).then(r=>r.json())

  const {data} : SWRResponse<Cat,string, string> = useSWR("https://xxxxxxxxxxxxx", fetcher)

The Fetcher type's first argument seems to be needing to match SWRResponse type's first argument.