Raphael
Raphael

Reputation: 11

How can useSWR return undefined when fallbackData is specified?

I am using useSWR within a Next.js application to fetch data on the client side to dynamically load data from an external API given a query parameter that specifies the language. However to ensure initial loading of the page, I retrieve data in a default language in getStaticProps and specify that data as fallbackData in useSWR. I then dynamically fetch data based on the currently selected locale using useSWR. The data returned by useSWR however is undefined despite the fact, that a fallback is specified.

function MyPage({ myFallbackData }) {
  console.log(myFallbackData) // myFallbackData is defined here
 
  const fetcher = async (url) => {
    let result = await fetch(url)
      .then((r) => r.json())
      .then((myFetchedData) => {
        console.log(myFetchedData) // myFetchedData is defined here 
        return myFetchedData
      })
    console.log("Saved Result")
    console.log(result)
  }

  const { data } = useSWR(
    `https://myapi.com?language=${i18n.language}`, 
    fetcher, 
    { fallbackData: myFallbackData }
  )
  console.log(data) // data is undefined here, however fallbackData was defined for useSWR

  export async function getStaticProps () {
    const res = await fetch('https://myapi.com?language=en') // retrieve default language
    const myFallbackData = await res.json()

    return {
      props: {
        myFallbackData
      }
    }
  }

  return <></>
}

I expect data to be defined at all times, either as the fallback data or as the fetched data for the specified language.

Upvotes: 0

Views: 1237

Answers (1)

Komo Rebi
Komo Rebi

Reputation: 11

you need to take getStaticProps out of the MyPage function. Also, I'd suggest you to take out fetcher as well and use it for both useSWR and getStaticProps. Let me know if you need any further support.

Upvotes: 0

Related Questions