[英]how yo use an async method inside useEffect() hook
I need to fetch an api in an useEffect()
.我需要在
useEffect()
获取一个 api。 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.
我尝试这样做,但它向我抛出以下错误:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
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: -Api 我需要获取:
export const fetchMyApi = async (code) => {
const { data } = await useQuery("data", () =>
clientAPIs.getData(code)
);
return data;
};
-My useEffect
code: - 我的
useEffect
代码:
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.
我正在使用Nextjs框架。
What should I try?我应该尝试什么?
Error: Invalid hook call.
错误:无效的挂钩调用。 Hooks can only be called inside of the body of a function component.
钩子只能在函数组件的主体内部调用。
You are breaking the rules of hooks.你打破了钩子的规则。 Hooks are only valid when called while synchronously rendering a React component.
钩子仅在同步渲染 React 组件时被调用时有效。 An effect runs separately after a componenent renders.
效果在组件渲染后单独运行。 So you cannot call a hook from an effect.
所以你不能从效果中调用钩子。
And yes you are calling a hook from an effect because this effect:是的,你正在从一个效果中调用一个钩子,因为这个效果:
useEffect(() => {
await fetchMyApi(values.code)
}, [values]);
Calls the fetchMyApi
function, which calls a hook:调用
fetchMyApi
函数,该函数调用一个钩子:
await useQuery('data', () => /* ... */)
You are using react query incorrectly.您错误地使用了反应查询。
First make your fetchMyApi
just do it's async task, and nothing else:首先让你的
fetchMyApi
只做它的异步任务,没有别的:
export const fetchMyApi = (code) => {
return clientAPIs.getData(code)
};
Then call useQuery
from the root of your functional component:然后从功能组件的根调用
useQuery
:
function MyComponent() {
const { data } = useQuery('data', () => fetchMyApi('some code here'))
}
The documentation should take you the rest of the way from here文档应该带你从这里开始
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.