Home > OS >  Storing All the data coming from API call based on some parameters in a List
Storing All the data coming from API call based on some parameters in a List

Time:11-09

I Have a list containing some ids, I have to call an api with each of ids in the list and store all the data that comes from the api in a list,I am mapping through the list and calling the api with each id and then pushing the data into an array,but when I finally check the array it gives inconsistent result,sometimes it returns all the data,some time some of the data or sometimes the list is empty,here is my react code

let deviceidlist=['eb77fa554fbdbed47dkubk','ebbaa8d217947ff4d1fk3w','ebe55d36879c7fd71emtf0','eb645acaa1efb456877nss','ebc32ad422bc5dc3eecapa','ebf5bb435e688e96e8mt5z','45102754e09806133d2d','eb7c72ba426f92b9a1pb81','eb84a574ecfa372e6ccapr','eb458f73adadf67170uxdv']
  
  let devicelist=[]
  useEffect(()=>{
   const datafetch=async()=>{
   deviceidlist.map((item)=>{fetch(`http://localhost:8000/api/switch/${item}`).then(data=>data.json()).then(data=>devicelist.push(data))})
   }

datafetch()
   

  
}
,[])
  
console.log(devicelist)

I am trying to store all the data that I get back from api to store in a list but getting an empty array

CodePudding user response:

Fetching data from API is an asynchronous task, consoling right after the API call may not give the expected result. That's the reason you are getting multiple results try adding the deviceList to a state so it will be

const[deviceList, setDeviceList] = useState([]);
  useEffect(()=>{
   const datafetch=async()=>{
   deviceidlist.map((item)=>{fetch(`http://localhost:8000/api/switch/${item}`).then(data=>data.json()).then(data=>{
setDeviceList([...deviceList, data]);
})})
   }
datafetch()
}
,[])

Try consoling the deviceList (state update will re-render the component and will console the updated data)

CodePudding user response:

Try to fetch the data asynchronously and then set it to the state instead of pushing it into the array. Something like this :

import React from 'react';
import { useState, useEffect } from 'react';

export default function App() {

  let deviceidlist = [
    'eb77fa554fbdbed47dkubk',
    'ebbaa8d217947ff4d1fk3w',
    'ebe55d36879c7fd71emtf0',
    'eb645acaa1efb456877nss',
    'ebc32ad422bc5dc3eecapa',
    'ebf5bb435e688e96e8mt5z',
    '45102754e09806133d2d',
    'eb7c72ba426f92b9a1pb81',
    'eb84a574ecfa372e6ccapr',
    'eb458f73adadf67170uxdv',
  ];

  const [deviceList, setdeviceList] = useState([]);


  useEffect( async() => {
    try {
      let response = await deviceidlist.map((item) => { fetch(`http://localhost:8000/api/switch/${item}`) })
      if (response.ok) {
        let data = await response.json()
        setdeviceList(data)
      } else {
        console.log("failed")
      }
    } catch(error) {
      console.log(error)
    }
  })

  return (
   <div></div>
  );
} 
  • Related