Struggling to implement GetServerSideProps with SWR, as the clientside keeps fetching data even though it's already loaded from the server side.
Here is an example scenario:
We retrieve a wordlist from the API based on word length in getServerSide/getStaticProps and SSR/SSG build the page for quick delivery.
User interacts with the page triggering
iterateWordLength()
.We then fetch an updated wordlist using
mutate
.
Current issue: SWR fires twice on load
- Serverside runs only once ✅
- Wordlist useEffect triggers - displays the word "foo" fetched by artificial getServerSideProps ✅
- WordClientSideFetcher also triggers ❌ (shouldn't because we already have the data)
Wordlist changed
event fires again ❌
I am avoiding useSWRImmutable due to dynamic fetcher and changing GET parameters based on another state variable.
Despite setting revalidate options to false, why does it still fire twice?
Below is a simplified version of Index.js:
function Index( { fallback } ) {
const [wordLength, setWordLength] = useState(DEFAULT_WORD_LENGTH);
const { data: wordlist, mutate } = useSWR('/api/wordlist', clientSideFetcher, {
fallbackData: fallback['/api/wordlist'],
revalidateIfStale: false,
revalidateOnMount: false,
revalidateOnFocus: false
})
}
useEffect(()=>{
// iterates word length
mutate() // updates wordlist
}, [wordLength])
useEffect(()=>{
console.log("### Wordlist changed")
setWord( generateRandomWord() )
},[wordlist])
const iterateWordlength = () => { setWordlength(wordLength+1)}
export async function staticFetcher() {
const res = await fetch(API_URL)
const data = await res.json()
console.log(`### staticFetcher fetched ${data.length} words`)
return new Wordlist(...data)
}
export async function getServerSideProps(context) {
const staticWordlist = await staticFetcher(context)
.catch( err => {
return { notFound: true }
})
const props = {
fallback: {
'/api/wordlist' : ["foo"]
}
}
return { props }
}