Home > Enterprise >  how to fetch data using .map() method with react Query(useQuries)
how to fetch data using .map() method with react Query(useQuries)

Time:10-18

I have multiple id's of array for API.

something likes:

const ids= [1001,1002,1003,1004,1005,
2001,2002,2003,2004,2005,
3001,3002,3003,3004,3005,
4001,4002,4003,4004,4005,
5001,5002,5003,5004,5005,
6001,6002,6003,6004,6005,
7001,7002,7003,7004,7005,
8001,8002,8003,8004,8005]

i'm using this id's end of the api to fetch data using .map() method. here is my codes:

const fetchDetails = () => {
    const requestArray = (ids?.map(async(id) => {
       return await axios.get(`https://www.roads.com/road/api/roadControl/${id}`, myHeaders)
       .then((res) => {
        return res.data;
    })
    }))
    return requestArray;
  }
  const finalData = useQueries({
    queries: [
      { queryKey: ['post', 1], queryFn: fetchDetails},
    ]
  })

  console.log(finalData);

here is my output by using this codes for fetching data enter image description here

so, as you can see here in output is showing me promise in array but i can't get the data. it's given me same as id's length promise. if anyone can help me to get the data.

if i use single id end of the API likes:

           return await axios.get(`https://www.roads.com/road/api/roadControl/1001`, myHeaders);

i can able to get the data for that specific api but when i use map to get all id's data to fetch, i can't able to view the data.

anyone can help me how to solve it or how can i able to view those data not promise. Thanks in advance for your trying!

S.N- i am using here false API for the purpose of security.

CodePudding user response:

This should help you resolve your promises : Promise.all

   Promise.all([yourpromises]).then((values) => {
      console.log(values);
    });

CodePudding user response:

try to return stringifyJSON(requestArray);

  • Related