I have a bunch of charts to display and need to load data separately for each of them.
The data structure identifying each chart is array and looks like this (subarray can host one or more charts. In case of multiple items in subarray, the chart will have multiple axis):
"charts":[["chart1"], ["chart2", "chart4", ...], ...]
There is not known in advance how many items will be in the array and how much they will have subitems.
My approach
First I go through charts and display placeholders (loaders), then if data state is available, display the chart:
const[data, setData] = useState(null);
return(
charts.map(item => {
(item in data && data[item] !== "") ? <Chart data={data[item]} /> : <Loader />
})
)
For the Axios data fetch I thought to use useEffect which would fill the data state variable, which would then re-render the component to show already loaded charts.
My issue here is, that I am not sure how to utilise useEffect to do this as calling Axios in a loop and setting data state variable in a loop does not seem right to me. I guess it would then create infinite loop.
The other a bit smaller question is, how to wait for data load of all subitems to display multiaxis chart, if it applies.
Based off the comments, here is an example of updating setData in a useEffect hook with the responses from multiple api calls to different endpoints:
const [data, setData] = useState([])
useEffect(() => {
const getData = async(url) => {
const res = await axios.get(url)
setData(prevState => [...prevState, res.data])
}
getData(url1)
getData(url2)
getData(url3)
}, [])