aribouius / jsonapi-react

A minimal JSON:API client and React hooks for fetching, updating, and caching remote data.
MIT License
149 stars 28 forks source link

How to set initialData? #32

Closed Steffi3rd closed 3 years ago

Steffi3rd commented 3 years ago

Hello guys 👋

I'm trying this lib using Next.js with SSR

I would like to set initialData as shown in this commit : https://github.com/aribouius/jsonapi-react/commit/b0e1960d1031497b7d876d71d668bec9c42ed93d, but I can't make it work, data of useQuery returns undefined at the first time :

export default function Index({ resultFromGetServerSideProps = "test" }) {
   const { data, meta, error, isLoading, isFetching } = useQuery([
      'news', {
        include: ['city'],
        initialData: resultFromGetServerSideProps,
      },
   ])

   console.log(data)
}

console.log : First render : undefined Re-render : { ... }

Someone knows how to set initialData please?

aribouius commented 3 years ago

Hey @Steffi3rd looks like you are passing initialData in the wrong place.

The signature of that hook is useQuery(query, options), so you're attempting to pass in an option param via the query arg.

The correct implementation would be

const { 
  data, 
  meta, 
  error, 
  isLoading, 
  isFetching 
} = useQuery(['news', { include: ['city'] }], {
  initialData: resultFromGetServerSideProps,
})
Steffi3rd commented 3 years ago

Oh yeah, my bad. Thank you very much @aribouius! It works now 😍


I just a Typescript error using initialData :

Capture d’écran 2021-05-21 à 10 04 04 Capture d’écran 2021-05-21 à 10 04 10
Steffi3rd commented 3 years ago

With @cta-faber, we've opened a PR to fix that : https://github.com/aribouius/jsonapi-react/pull/34