[英]ASYNC call of custom hook in React
I have got a problem with async
calls and my custom hook in React. 我在async
调用和React中的自定义钩子方面遇到了问题。
I need to call a series of fetch from the same custom hook, but it's not respecting the await chain. 我需要从相同的自定义钩子调用一系列访存,但它不遵守等待链。
I've some buttons that work onClick
like this: 我有一些可以像onClick
这样工作的按钮:
buttonDelete={() => deleteAssignedOpp(opportunity.id)}
async function deleteAssignedOpp(id) {
await doFetch(`/opportuniy/assigned/${id}`, "DELETE");
await doFetch("/opportuniy/assigned/list", "GET", "IN_PROGRESS");
}
Those buttons are calling a custom hook, like this: 这些按钮调用自定义钩子,如下所示:
(I got some of this code from online tutorials) (我从在线教程中获得了一些代码)
function useFetch() {
const [url, setUrl] = useState("");
const [obj, setObj] = useState("");
const [method, setMethod] = useState("GET");
const [body, setBody] = useState();
const [state, dispatch] = useStateValue();
useEffect(() => {
let didCancel = false;
if (url) {
const fetchData = async () => {
dispatch({
type: `FETCH_${obj}_INIT`
});
try {
const response = await fetch(
`https://myapiAddress${url}`,
{
method: method,
//body: body,
headers: new Headers({
Authorization: myFunctionForAuthorization
})
}
);
const result = await response.json();
if (!didCancel) {
dispatch({
type: `FETCH_${obj}_SUCCESS`,
payload: result
});
}
} catch (error) {
if (!didCancel) {
dispatch({
type: `FETCH_${obj}_ERROR`,
payload: { error }
});
}
}
};
fetchData();
return () => {
didCancel = true;
};
}
}, [method, body]);
const doFetch = (url, method, obj, body = "") => {
setUrl(url);
setObj(obj);
setMethod(method);
setBody(body);
};
return [doFetch];
}
export default useFetch;
I expect the custom hook to be called in the same order of button async/await
function. 我希望以与按钮async/await
功能相同的顺序调用自定义钩子。
Thanks a lot. 非常感谢。
You could try Promise.all in your useEffects hook . 您可以在useEffects挂钩中尝试Promise.all。 Each fetch will return a promise 每次获取都会返回一个承诺
Promise.all([api1,api2]).then(function(values){
console.log(values)
});
Would that work. 那行得通。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.