[英]Async/Await Multiple Functions dependent on async data
I am creating a ReactJS app and trying to write a function that creates a set of categories.我正在创建一个 ReactJS 应用程序并尝试编写一个创建一组类别的 function。 This data is coming from an
api
.此数据来自
api
。
const data = [
{
name: '',
category = 'sports'
},
{
name: '',
category = 'food'
},
]
I wrote a function that gets the data.我写了一个 function 来获取数据。
const getData = async()=>{
const data = await fetch(url);
// json conversion
setData(data);
}
However to filter this data array, i need to pass data to another filter function.但是要过滤这个数据数组,我需要将数据传递给另一个过滤器 function。 How do i do that so that my data array passes with filled value and not the initial empty array?
我该怎么做才能使我的数据数组以填充值而不是初始空数组传递?
const filterData = ()=>{
// data is global
const categories = [new Set(data.map((item) => item.category))]
}
How do I call this function after my data array is ready?在我的数据阵列准备好后,如何调用这个 function? Or how to get the desired result.
或者如何得到想要的结果。
Simple, call the filter function after you have got the data,很简单,拿到数据后调用过滤器function,
const getData = async()=>{
const data = await fetch(url);
// json conversion
setData(data);
// Call filter from here
filterData (data)
}
This is the simplest and most straightforward approach.这是最简单、最直接的方法。 Another way would definitely be to watch for the data change (with useEffect dependency), but that can be an overkill for a simple task IMO.
另一种方法肯定是监视数据更改(使用 useEffect 依赖项),但这对于简单的 IMO 任务来说可能是过度杀伤力。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.