[英]getting data from browser indexed db then call api
I have the following useEffect call back function:-我有以下 useEffect 回调 function:-
import { initDB, useIndexedDB } from "react-indexed-db";
initDB(DBConfig);
const db = useIndexedDB("reads");
useEffect(() => {
db.getByIndex("hash", props.match.params.id).then((data) => {
setToken(data.token);
});
handleTextColorSelection(backgroundColor);
axios
.post(`${process.env.REACT_APP_API_URL}khatma/read`, {
khatma: props.match.params.id,
part: props.match.params.part,
section: props.match.params.section,
token: token,
})
.then((res) => {
if (res.data.token) {
db.add({
hash: props.match.params.id,
token: res.data.token,
}).then(
(event) => {},
(error) => {
console.log(error);
}
);
}
})
In axios post body i am sending token, if "token" state receive a value stored before in browser indexed db, if there is not object store data found, then a post token will be sent as null. In axios post body i am sending token, if "token" state receive a value stored before in browser indexed db, if there is not object store data found, then a post token will be sent as null.
The problem here, that i noticed that before the db.getByIndex("hash", ... command get a result, an axios request run, and sending a token as null, even-though later on token state will get a value.这里的问题是,我注意到在 db.getByIndex("hash", ... 命令得到结果之前,运行 axios 请求,并发送一个令牌为 null,尽管稍后在令牌 Z9ED39E2EA931586B73EZA 上会得到一个值
How can i run the db.getByIndex("hash", then if it finish, run axios post request?我如何运行 db.getByIndex("hash",然后如果它完成,运行 axios 发布请求?
You could use .then
你可以使用
.then
const axiosRequest = () => { /* your axios logic */ };
db.getByIndex(...).then(axiosRequest).catch(axiosRequest)
Anything you do inside the then
and catch
callbacks will be run after the getByIndex
call您在
then
和catch
回调中执行的任何操作都将在getByIndex
调用之后运行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.