How can I pass an authorization header to all queries and mutations
Hello
I have this code that allow to me pass my token to all my queries and it works fine. But I'd like this for my mutations too if possible.
This is a query example
But I'd like to do the same my my mutations:
I have this code that allow to me pass my token to all my queries and it works fine. But I'd like this for my mutations too if possible.
function RootLayoutNav() {
const { session } = useSession();
const queryClient = new QueryClient({
defaultOptions: {
queries: {
queryFn: async ({ queryKey }) => {
const token = await session?.getToken();
const response = await fetch(`${queryKey[0]}`, {
headers: {
Authorization: token ? `Bearer ${token}` : "",
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
},
},
},
});
return (
<QueryClientProvider client={queryClient}>
<Whatever/>
</QueryClientProvider>
);
}function RootLayoutNav() {
const { session } = useSession();
const queryClient = new QueryClient({
defaultOptions: {
queries: {
queryFn: async ({ queryKey }) => {
const token = await session?.getToken();
const response = await fetch(`${queryKey[0]}`, {
headers: {
Authorization: token ? `Bearer ${token}` : "",
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
},
},
},
});
return (
<QueryClientProvider client={queryClient}>
<Whatever/>
</QueryClientProvider>
);
}This is a query example
export const useCompanyShifts = (companyId: string) => {
return useQuery<ShiftWithRelations[]>({
queryKey: [`${API_BASE_V1}/company/${companyId}/shifts`],
enabled: !!companyId,
});
};export const useCompanyShifts = (companyId: string) => {
return useQuery<ShiftWithRelations[]>({
queryKey: [`${API_BASE_V1}/company/${companyId}/shifts`],
enabled: !!companyId,
});
};But I'd like to do the same my my mutations:
export const useCreateShift = () => {
return useMutation<Shift, Error, Partial<NewShift>>({
mutationFn: (data) =>
fetch(`${API_BASE_V1}/shifts`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
}).then((res) => res.json()),
});
};export const useCreateShift = () => {
return useMutation<Shift, Error, Partial<NewShift>>({
mutationFn: (data) =>
fetch(`${API_BASE_V1}/shifts`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
}).then((res) => res.json()),
});
};