简体   繁体   English

存储来自 axios 的数据以便稍后通过 util 函数使用

[英]Storing data from axios to use it later via util functions

I have a simple axios GET call, which I would like to store for later use by some util functions.我有一个简单的 axios GET 调用,我想将其存储起来以供某些 util 函数以后使用。 As this is a react app, could it be stored in memory (browser) or in a file in a dir?由于这是一个反应应用程序,它可以存储在内存(浏览器)或目录中的文件中吗?

const data = [];

const getData = (logName) => {
  if (logName === '') {
    alert('Please enter the name of your log!');
  } else {
    axios({
      method: 'GET',
      url: `http://xxx-yyy-zzz/debugger/RTS/${logName}/logs`,
    })
      .then((res) => {
        alert('Successfully Imported');
        return data.push(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
};

const askPrice = () => {
  return data.map((result) => result.request.requestContext.mpcBidRequest.askPrice);
};

This is what I currently have, previously data was just import data from '../data/x.json';这是我目前拥有的,以前的data只是import data from '../data/x.json'; But now I would like to call the request and replace import data from '../data/x.json';但是现在我想调用请求并替换import data from '../data/x.json'; with the returned data from the GET response.使用从 GET 响应返回的数据。

The function...功能...

const askPrice = () => {
  return data.map((result) => result.request.requestContext.mpcBidRequest.askPrice);
};

Will be used later (after calling the API) to then map over the array of JSON objects to output the results to a UI.稍后将使用(在调用 API 之后)然后映射 JSON 对象数组以将结果输出到 UI。 My app works perfectly well using import data from '../data/x.json';我的应用程序使用import data from '../data/x.json';运行良好import data from '../data/x.json'; but now I want to get user input to generate the data.但现在我想获取用户输入来生成数据。

I have managed to store what i need into a let and have tested things...everything works ok.我已经设法将我需要的东西存储到一个let并测试了一些东西......一切正常。

let data = [];

async function getData(filter, logName) {
  if (logName === '') {
    alert('Please enter the name of your log!');
  } else {
    axios({
      method: 'GET',
      url: `http://xxx/debugger/${filter}/${logName}/logs`,
    })
      .then((res) => {
        if (res.data.length === 0) {
          console.log(res.data);
          alert('Your query returned empty JSON!');
        } else {
          console.log(res.data);
          data = res.data;
        }

        return res.data;
      })
      .catch((err) => {
        console.log(err);
      });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM