T
TanStack2y ago
environmental-rose

useQuery with different queryKey

so basically guys im trying to fetch an api using react query and i find my self doing some reptitive code durning the fetch so i decide to make this :
const fetchData = async ({ queryKey }) => {
try {
const res = await axios.get(
`${import.meta.env.VITE_BASE_URL}tv/${queryKey[0]}`,
{
params: {
api_key: import.meta.env.VITE_API_KEY
},
}
);
if (!res) {
throw new Error("response not work");
}
const data = await res.data;
return data;
} catch (error) {
console.log("Error", error);
}
};
export const useFetchData = (series_id) => {
return useQuery({
queryKey: [`${series_id}`],
queryFn:fetchData,
});
}
const fetchData = async ({ queryKey }) => {
try {
const res = await axios.get(
`${import.meta.env.VITE_BASE_URL}tv/${queryKey[0]}`,
{
params: {
api_key: import.meta.env.VITE_API_KEY
},
}
);
if (!res) {
throw new Error("response not work");
}
const data = await res.data;
return data;
} catch (error) {
console.log("Error", error);
}
};
export const useFetchData = (series_id) => {
return useQuery({
queryKey: [`${series_id}`],
queryFn:fetchData,
});
}
and inside my component like this :
const { status: status1, data: details } = useFetchData(`${id}`);
const { status: status2, data: casts } = useFetchData(`${id}/credits`);
const { status: status3, data: recommendation } = useFetchData(
`${id}/recommendations`
);
const { status: status1, data: details } = useFetchData(`${id}`);
const { status: status2, data: casts } = useFetchData(`${id}/credits`);
const { status: status3, data: recommendation } = useFetchData(
`${id}/recommendations`
);
so is there any error in my code or some future probleme that i will face
2 Replies
optimistic-gold
optimistic-gold2y ago
It works but your query key is not legible Do queryFn: ()=>fetchData(series_id) instead
environmental-rose
environmental-roseOP2y ago
yeah ok

Did you find this page helpful?