This is my useQuery hook:
const { isLoading: isBskLoading, refetch: refetchBskData } = useQuery(
"bskFixturesData",
() => {
instance.get(`/basketball/matches/${date}`).then((res) => res.data);
},
{
onSuccess: (jsonData) => {
setBskData(jsonData);
setHasBskData(true);
},
refetchOnWindowFocus: false,
enabled: false,
}
);
I want to call the refetchBskData()
function from a different component in my project, and I am able to do so, but I am unable to figure out how to pass date variables through the refetchBskData()
function, which can be accessed in the useQuery
hook above.
This is my code, which calls the refetchBskData()
useEffect(() => {
let date = new Date(location.state.date);
let formattedDate = date.toLocaleDateString("en-GB");
refetchBskData()
}, [refetchBskData, location]);
Any ideas on how to pass the formattedDate
?
useQuery is reactive like any other hook, so it watches changes in your render. If you pass any state to the queryKey
, it should re-fetch the data automatically if the variable changes. Don't be afraid to calculate location right before you use a hook, react-query
caches any deps، so don't handle this in useEffect
.
const [date, setDate] = React.useState(new Date())
const { data } = useQuery(["test", date], ({ queryKey: [_key, date] }) => {
return date
})
const handleAddYear = () => {
const newDate = new Date(date.setFullYear(date.getFullYear() + 1))
setDate(newDate)
}
return (
<div>
<button onClick={handleAddYear}>Press to add a year</button>
<div>
{data?.toISOString()}
</div>
</div>
);
In you case you should do next:
export function useFetchBskData(date) {
return useQuery(
["bskFixturesData", date],
async ({ queryKey: [_key, date] }) => {
const response = await instance.get(`/basketball/matches/${date}`);
return response.data;
},
{
refetchOnWindowFocus: false
}
);
}
Or:
const date = new Date(location.state.date);
const formattedDate = date.toLocaleDateString("en-GB");
const { isLoading: isBskLoading } = useQuery(
["bskFixturesData", date],
({ queryKey: [_key, date] }) => {
return instance.get(`/basketball/matches/${date}`).then((res) => res.data);
},
{
onSuccess: (jsonData) => {
setBskData(jsonData);
setHasBskData(true);
},
refetchOnWindowFocus: false,
enabled: false,
}
);