-8

When i am trying to fetch multiple API using map() method, and launch the project it's given me empty which is i understand my console.log couldn't able to fetch at the time, and just use Ctrl+s press to save the file again, it's start to giving me value in react native vs code. in this case how can i avoid to launch the project and again Ctrl+s press. what should i use to avoid them and once i launch, i will able to fetch the data.

i already have tried setinterval but it's repeating me empty array, the setinterval isn't reach to fetch again.

should i try any function for it or something?

here is my code in vs code:

const [dataLoc, setDataLoc] = useState([]);
const ids = [1,2,3,4,5];

useEffect(() => {
  ids?.map((id) => {
    fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
      .then((response) => response.json())
      .then((dataLoc) => setDataLoc((prev) => [...prev, dataLoc.title]))
      .catch((error) => console.error(error));
  });
}, []);

console.log(dataLoc);

when i tried it to run in vs code i get this problem as i mention already.

Anyone can help me? i'm stack at the place for a long time. i appreciate your trying. Thanks for your trying in advance!

  • It'd be nice if you paste the code so it's easier to understand what you're trying to do – gustavozapata Oct 21 '22 at 08:10
  • i already add my code here – Botol Shuvo Oct 21 '22 at 08:13
  • I have no idea what you are talking about – Fabio Oct 21 '22 at 08:14
  • it's giving me empty array for the first console.log(), i can't able to view my data when i launch the project. – Botol Shuvo Oct 21 '22 at 08:14
  • try this code in VS Code framework to check please – Botol Shuvo Oct 21 '22 at 08:16
  • Your question is hard to understand... What exactly are you asking: Why your state is an empty array on the first render? Why the fetch and state setting is not working as expected? Please clarify. – ivanatias Oct 21 '22 at 08:18
  • 1
    Ok, first you need to modify your fetching approach... The promises won't be awaited if you fetch the data using `map` like that. You should be using `Promise.all`, `Promise.allSettled` or even a `for...of` loop if you want the calls to be made sequentially. – ivanatias Oct 21 '22 at 08:27
  • @PeterTam i tried as you said but still it's same – Botol Shuvo Oct 21 '22 at 08:29
  • @ivanatias as simple as it is that when i tried to fetch data, it's giving me empty array, inside array should be data from api. you can tried this code in vs code, online emulator is works so please try in vs code. – Botol Shuvo Oct 21 '22 at 08:30
  • You are putting your `console.log()` directly in your default export function. That means when you set any state in this functional component. It will re-render once and `log()` will be called. – kiuQ Oct 21 '22 at 08:32
  • @ivanatias if you can help me kindly to modify my code, because i used before Promise.all but i couldn,t make it. – Botol Shuvo Oct 21 '22 at 08:33
  • Try `Promise.all` to make requests in a loop (in your case inside a map). There are some examples online – gustavozapata Oct 21 '22 at 08:33
  • useEffect(() => { Promise.all(devices?.map(async (id) => { return new Promise((resolve) => { fetch(`https://jsonplaceholder.typicode.com/posts/${id}`) .then((response) => response.json()) .then((dataLoc) => setDataLoc((prev) => [...prev, dataLoc.title])) .catch((error) => console.error(error)) }) })) }, []); i tried Promise all it's giving me ( " ERROR TypeError: Array.from requires an array-like object - not null or undefined" ) this error – Botol Shuvo Oct 21 '22 at 08:43

2 Answers2

0

You may try the Promise.all() approach mentioned in comments above.

useEffect(() => {
 fetchData();
}, []);

async function fetchData(){
  const requestArray = await Promise.all(ids?.map((id) => {
    return fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
      .then((response) => response.json())
      .then((dataLoc) => {
        return dataLoc.title;
      })
      .catch((error) => console.error(error));
  }));

  console.log(JSON.stringify(requestArray));
  setDataLoc(requestArray);
}
kiuQ
  • 931
  • 14
0

To avoid Warn: Possible unhandled Promise Rejection (id:0)

   useEffect(() => {
     fetchData();
    }, []);
    
    async function fetchData(){
    
    try{
const requestArray = await Promise.all(ids?.map((id) => {
        return fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
          .then((response) => response.json())
          .then((dataLoc) => {
            return dataLoc.title;
          })
          .catch((error) => console.error(error));
      }));
    
      console.log(JSON.stringify(requestArray));
      setDataLoc(requestArray);
    }
    catch (error) {
                console.log(error);
            }
     }