I'm working on a dashboard that makes several calls (3) to an API. In order to synthesize the code i used the AXIOS library with the AXIOS.all fonction.
- call No1 & 2: we query a table of data
- call No3: Count
This code consults the profile of a user and its data. Some users have data and some don't. The calls work when the user has data and return a 404 error when the user doesn't.
In practice: when one of the calls fails to return data (error) then all the code is blocked.I imagine that it is the consequence of AXIOS.ALL..
So I had the following idea:
Create a first request that will verify a specific data on the API and set up a condition with if and else: if I receive an error then displays the following message in the div <div>message</div> of the body. Otherwise you can run all queries.
const AccountTab = () => {
const [datalist, setDatalist] = useState([]);
const [count, setCount] = useState();
const [infoscount, setInfoscount] = useState([]);
const [loading, setLoading] = useState(false);
const mounted = useRef(true);
useEffect(() => {
setLoading(true);
const fetchData = async () => {
const resultdata = await axios.get(getData(address));
const resultcount = await axios.get(countData(address));
const resultstuffcount = await axios.get(InfosStuff(address));
axios.all([resultdata, resultcount, resultstuffcount]).then(
axios.spread((...allData) => {
const allData = allData[0].data; /* array */
const allDataCount = allData[1].data; /* count */
const allDataStuffCount = allData[2].data.count;
/* We get an array but we retrieve the row 'count' -> count*/
setDatalist(allData);
setCount(allDataCount);
setInfoscount(allDataStuffCount);
})
);
};
if (mounted.current) {
setLoading(false);
}
fetchData();
}, []);
return ()
};