I am trying to implement swr library for my data fetching. I used to use plain axios and some custom hooks I created. The problem I am having is that for some reason, swr is firing the get request before the default axios header is set, thus missing on sending a header that is needed to identify the account for my application. My guess is that it has to do with the prefetch capabilities of SWR but that is just a wild guess and don't know how to prevent this from happening.
import axios from "axios";
import React, {useLayoutEffect} from "react";
import useSWR from "swr";
function Child({match}) {
const fetcher = () => {
console.log('Should happen second')
axios.get('https://api.mydomain.com').then(res => res.data)
}
const {data} = useSWR('/account/specific/data', fetcher)
return <div>{JSON.stringify(data)}</div>
}
export default function Account({match}) {
let accountId = match.params.accountId;
useLayoutEffect(() => {
console.log('Should happen first')
axios.defaults.headers.common["Account-Token"] = accountId;
}, [accountId]);
return <Child/>
}
You are getting your sequences wrong imo.
1) You should probably return null if your component is not ready to be generated.
export default function Account({match}) {
let accountId = match.params.accountId;
useLayoutEffect(() => {
console.log('Should happen first')
axios.defaults.headers.common["Account-Token"] = accountId;
}, [accountId]);
if (!accountId) return null //<-- don't generate the Child component until you are ready.
return <Child/>
}
2) If you really want to disable SWR fetch on mount, it's to set { revalidaOnMount: false }
e.g.
const {data} = useSWR('/account/specific/data', fetcher, { revalidateOnMount: false})
3) Or you can use conditional fetching so it fetches only when your variable is ready.
const { data } = useSWR( accountID ? /url/path : null, fetcher )
The useSWR hook will not call the fetcher when the key is null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With