I need to fetch an api in an useEffect()
. I tried to do it and it throws me the following error: Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
My code is the following:
-Api I need to fetch:
export const fetchMyApi = async (code) => {
const { data } = await useQuery("data", () =>
clientAPIs.getData(code)
);
return data;
};
-My useEffect
code:
useEffect(() => {
await fetchMyApi(values.code)
}, [values]);
I have found many issues about this on internet but they all offer basically the same solution such as:
useEffect(() => {
fetchMyApi(values.code)
.then((data) => {
return data?.options;
})
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
});
}, [values]);
or
useEffect(() => {
let didCancel = false;
async function fetch() {
const result = await fetchMyApi(values.code);
if (!didCancel) {
console.log(result);
}
}
fetch();
return () => {
didCancel = true;
};
}, [values]);
None of those works in my case. I am using Nextjs framework.
What should I try?