I have a api that only uses POST, so i have to sent an ID to fetch, in this case event.
The problem is that my SWR is making infinite calls.
I have this component:
const EventDetail = ({ params }: { params: { id: string } }) => {
const id: string = params.id;
const [cookies] = useCookies(["token"]);
const token = cookies.token;
let formData = new FormData();
formData.append("id", id);
const dataToRequest = { token, formData };
const { data, error, isLoading } = useSWR(
[SERVICESADDR.EVENT, dataToRequest],
fetcher,
);
if (error) {
console.log(error);
}
console.log(data);
return <div>{id}</div>;
};
export default EventDetail;
and my fetcher is:
export const fetcher = ([url, data]: [
url: string,
data: { token: string; formData?: FormData },
]) =>
fetch(url, {
method: "POST",
body: data.formData,
headers: {
Authorization: `Bearer ${data.token}`,
"Accept-Language": "pt",
Accept: "/*",
},
})
.then((res) => res.text())
.then((res) => res);
Thank you in advance!!
This is because the
key(first argument ofuseSWR) is tied to the cache key.If any value in this array is updated, a new http request will be triggered.
In your example, the key is
[SERVICESADDR.EVENT, dataToRequest]anddataToRequestobject is recreated at each render, that's why you get an infinite service call.You can pass the
tokenand theidto key and create theFormDataobject in thefetcherfunction