[英]React PUT and GET axios request in 1 function
I have 2 custom hooks.我有 2 个自定义挂钩。 1 to PUT data, the other to GET the data.
1 用于 PUT 数据,另一个用于 GET 数据。 I need to retrieve the data immediately after it has been PUT to route the user and handle any errors.
我需要在 PUT 后立即检索数据以路由用户并处理任何错误。 With what I have below, the actions happen to fast and GET happens before PUT.
有了我下面的内容,动作发生得很快,GET 发生在 PUT 之前。 Any way around this?
有什么办法吗?
const { update, fetch, data, loading, success } = useFoo(data);
const OnClickHandler = () => {
update();
if (success === 200) {
fetch();
// do some checks and if ok route
} else {
// do something else
}
};
const fetch = useCallback(() => {
setLoading(true);
axios({
url: url,
headers: foo,
method: "get"
})
.then((response) => {
setLoading(false);
setSuccess(response.status);
setData(response.data);
})
.catch((error) => {
setLoading(false);
});
}, [setSuccess]);
const update = useCallback(() => {
setLoading(true);
axios({
url: url,
headers: foo,
method: "put",
data: data,
responseType: "json"
})
.then((response) => {
setLoading(false);
setSuccess(response.status);
console.log(response);
})
.catch((error) => {
setLoading(false);
});
}, [data]);
If you want to wait for the end of certain calls, you must mark the function as async and wait for the function call.如果要等待某些调用结束,则必须将函数标记为异步并等待函数调用。
I tried to anticipate the structure of your useFoo() hook, and here are my changes:我试图预测您的useFoo()挂钩的结构,以下是我的更改:
const useFoo = (data) => {
const [ loading, setLoading ] = React.useState(false)
const [ success, setSuccess ] = React.useState()
const [ data, setData ] = React.useState()
const [ error, setError ] = React.useState()
const fetch = React.useCallback(async () => {
setLoading(true)
await axios({
url, // TODO: pass your url
headers: {}, // TODO: pass your headers
method: 'get'
})
.then((response) => {
setSuccess(response.status)
setData(response.data)
})
.catch((error) => {
setError(error)
})
.finally(() => setLoading(false))
}, [ setSuccess ])
const update = React.useCallback(
async () => {
setLoading(true)
await axios({
url, // TODO: pass your url
headers: {}, // TODO: pass your headers
method: 'put',
data,
responseType: 'json'
})
.then((response) => {
setSuccess(response.status)
})
.catch((error) => {
setError(error)
})
.finally(() => setLoading(false))
},
[ data ]
)
return {
data,
fetch,
loading,
success,
update,
error
}
}
The component that uses the hook might look something like this:使用钩子的组件可能看起来像这样:
const YourComponent = () => {
const { update, fetch, data, success } = useFoo(foo)
const onClickHandler = async () => {
await update()
if (success === 200) {
await fetch()
// do some checks and if ok route
} else {
// do something else
}
}
return null
}
The await
keyword forces the function to block until the function call is finished. await
关键字强制函数阻塞,直到函数调用完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.