【问题标题】:getting data from browser indexed db then call api从浏览器索引数据库获取数据然后调用 api
【发布时间】:2020-10-20 00:51:51
【问题描述】:

我有以下 useEffect 回调函数:-

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);
                }
              );
            }
    })

在 axios 帖子正文中我发送令牌,如果“令牌”状态接收到之前存储在浏览器索引数据库中的值,如果没有找到对象存储数据,则帖子令牌将作为 null 发送。

这里的问题,我注意到在 db.getByIndex("hash", ... 命令获得结果之前,axios 请求运行,并将令牌发送为空,即使稍后令牌状态会得到一个值。

如何运行 db.getByIndex("hash",然后如果它完成,运行 axios post request ?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你可以使用.then

    const axiosRequest = () => { /* your axios logic */ };
    
    db.getByIndex(...).then(axiosRequest).catch(axiosRequest)
    

    您在thencatch 回调中执行的任何操作都将在getByIndex 调用之后运行

    【讨论】:

    • 这个问题,如果getByIndex失败,我也想提出axios请求,我应该写两次,在then和catch下?
    • 我希望axios请求在两种情况下运行,一种如果用户浏览器数据库中没有存储令牌,则使用空令牌发送请求,如果存储令牌,则发送存储的令牌
    • 是的,您也可以在 catch 块中执行 axios 请求。我编辑了我的答案以反映这一点
    • 为了防止你的axios请求逻辑代码重复,可以做我刚刚编辑的代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 2012-02-17
    • 2021-10-18
    相关资源
    最近更新 更多