Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

reactjs - how to modify database data after fetching it in react

I have a few js that only contain export const and those are not any class or function. I have an async-await function to fetch data from the database. Now I need to create another const that will only fetch the first data from the result. and there is another const where I need to set that data.

data fetching const in db.js

export const getLatestData = async () => {
  const url = `${testDB.serverUrl}/findLatestTen`;
  const res = await axios.get(url).then(res => res);
  return res;
};

I have another function that will retrieve only the first value

export const getFirst = async () => {
  const test = await getLatestData();
  const example = test.data[0].salary;
  // If I put console.log here I get the example value as expected
};

But I have another js file called employee.js where I have some const like this

export const details = [
  {
    title: 'HR',

    links: [
      {
        title: 'Employee 1',
        salary: async () => {
          await getFirst();
        }
      },
      {
        title: 'Employee 2',
        salary: async () => {
          await getFirst();
        }
      }
    ]
  }
];

I will use this employee.js to set value in the UI. But I am not getting the value. Can I please get some help?

TIA


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

await getFirst() will just run the function. If you want to get the you should return the function.

export const getFirst = async () => {
  const test = await getLatestData();
  const example = test.data[0].salary;
  return example; // return value
};
export const details = [
  {
    title: 'HR',

    links: [
      {
        title: 'Employee 1',
        salary: async () => {
          return await getFirst();  // return function result
        }
      },
      {
        title: 'Employee 2',
        salary: async () => {
          return await getFirst();  // return function result
        }
      }
    ]
  }
];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...