0
const devices = [1001, 1002, 1003];
const fetchData = () => {
     const fP = devices?.map(async (id) => {
        const { data } = await axios.get(`https://www.roads.com/road/ap/roadControl/${id}`, myHeaders);          
        return data.data;
    })

    return (fP);
};


const {data} = useQuery ("post", fetchData);
console.log(data);

In this following codes, I'm tring to fetch data from 3 API's using .map() method to change id's end of the API.

but using axios inside map method, i can't fetch the data from the API. if i don,t use .map() method, i can fetch the data without any issues.

something Like that:

const { data } = await axios.get(`https://www.roads.com/road/ap/roadControl/1001`, myHeaders); 

If i use .map() method and inside use axois i can't fetch the data. i get undefined.

so how can i fix this issues, any can help me to fix it.

what should i do to fix it?

ThankYou for your trying in advance!.

for my security reason i'm using here false api so you can use to work something valid api.

Sabbir Ahhmed
  • 69
  • 1
  • 7
  • Just change the `return` to `Promise.all(fP)` – Phil Oct 17 '22 at 03:49
  • still it undefined for the reload files. – Sabbir Ahhmed Oct 17 '22 at 04:56
  • Sorry, I have no idea what that means – Phil Oct 17 '22 at 04:58
  • If the `devices` array is required by the query, you should be providing it as part of the [query key](https://tanstack.com/query/v4/docs/guides/query-keys#if-your-query-function-depends-on-a-variable-include-it-in-your-query-key) – Phil Oct 17 '22 at 05:01
  • actually when i reload emulator it's given me undefined but if i save the files after reload emulator, everything is working fine so first lunch app is giving me an error. – Sabbir Ahhmed Oct 17 '22 at 06:40

1 Answers1

-1

I would suggest you to try Promise.all() while fetching multiple API data at the same time.

const fetchData = async() => {
  const devices = [1001, 1002, 1003];

  const requestArray = await Promise.all(devices?.map((id) => {
     return axios.get(`https://www.roads.com/road/ap/roadControl/${id}`, myHeaders);
  }))

  console.log( JSON.stringify(requestArray) );
}

Since I do not have the header information, I cannot reproduce an example which is confirmed working. You can extract your data in requestArray instead of working in the map().

kiuQ
  • 931
  • 14