【问题标题】:How React js & LocalStorage with Axios API response?React js & LocalStorage 如何与 Axios API 响应?
【发布时间】:2020-11-05 16:34:52
【问题描述】:

我正在开发 React 应用程序, 通常用户登录并提交表单和表单的地方有多个字段,即选择即下拉字段,

每当用户登录系统时,

login = async (data = {}) => {
    try {
      // const { token, user } = await login(data);

      const { access_token, expires_at } = await login(data);
      const token = access_token;
      localStorage.setItem("token", token);
      const authToken = localStorage.getItem("token");

      const config = await getConfig(authToken);
      localStorage.setItem("config", JSON.stringify(config));

      initAxios();

      this.setState(
        {
          token,
        },
        () => {
          notify({
            type: "success",
            text: "Successfully logged in!",
          });
        }
      );
    } catch (error) {
      if (error.response.status === 401) {
        throw error;
      }
      notify({
        type: "error",
        text: getErrorMessage(error),
      });
    }
  };

我想在我可以获得这个对象的多表单组件中使用它,

从本地存储中检索数据的最佳解决方案是什么?

const configData = JSON.parse(localStorage.getItem("config"));
export const category = configData.category;
export const gender = configData.gender;
......



&从组件中导入并使用,

是否可以在 useEffect() hooks 的帮助下直接在表单组件中使用它?

在此处添加代码片段@Arnab

if (localStorage.getItem("apiData")) { 
accessoriesConfig = JSON.parse(localStorage.getItem("apiData")); return accessoriesConfig; }
else{ 
return fetchOptions().then(response => localStorage.setItem("apiData", JSON.stringify(response)));
//this is returns me always promise as pending status ,that breaks my functionality 

} 
//API Call with axios
export async function fetchOptions() {
return getAxios("get","/api/config/") .then(response => response.data); 
} ```  

【问题讨论】:

  • 我没听懂你的问题。

标签: javascript reactjs


【解决方案1】:

如果您从您的 api 获得 json 响应,那么您可以通过选择器将数据保存在 Localstorage 中,这样您以后更容易检索。

axios({
    url: 'APIplaceholder'
    adapter: jsonpAdapter
  }).then((res) => {     
        localStorage["name"]=res.data.name
        localStorage["email"]=res.data.email
  });

在这种情况下,当您尝试检索时,您可以像这样按键调用 localstorage.get() 函数::

localStorage.getItem("name")

否则您可以将整个响应作为字符串保存到本地存储,例如:

axios({
        url: 'APIplaceholder'
        adapter: jsonpAdapter
      })
.then((res) => {
     localStorage.setItem("apiData", JSON.stringify(res.data));
});

并像这样检索:

var data = JSON.parse(localStorage.getItem("apiData"));

然后使用 dot(.) 操作符作为对象访问它们。 data.name

【讨论】:

  • 快乐是我的。希望答案有帮助
  • 嗨@Arnab,我正在尝试保存用户登录时的api响应,但我想在下面尝试,``` lang-js if (localStorage.getItem("apiData")) { AccessoriesConfig = JSON.parse(localStorage.getItem("apiData"));返回附件配置; }else{ return fetchOptions().then(response => localStorage.setItem("apiData", JSON.stringify(response)));这是返回我始终承诺为待处理状态,这破坏了我的功能} export async function fetchOptions() { return getAxios("get","/api/config/") .then(response => response.data); } ```
  • 您可以将其分享为答案或格式化的其他 sn-p 吗?现在很难理解
  • 是的,我修改了帖子并在底部添加了代码,在评论部分我无法突出显示代码@Arnab
  • getAxios("get","/api/config/") .then(response => response.data);这里得到API响应后,需要存储到localstorage
【解决方案2】:

我在这里应用的解决方案如下,

export async function fetchOptions() {
    var configData = JSON.parse(localStorage.getItem("config"));
    if(configData){
      return configData;
    }else{
    return getAxios("get","/api/config/")
      .then(response => {      
        localStorage.setItem('config',JSON.stringify(response.data));
        return response.data;
      });
    }
  }


Importing in Components and Files.

import {fetchOptions} from '../../requests';
var configData = JSON.parse(localStorage.getItem("config"));
if(!configData) {
  fetchOptions().then(res => {
    setConfigValue(JSON.parse(localStorage.getItem("config")));
  });
}else{
  setConfigValue(configData);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-29
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多