Search code examples
javascriptreactjsforeachaxiosuse-effect

I want to use axios with foreach in useEffect react Js but it gives me (cannot read property Symbol(Symbol.iterator) error?


I want to call axios in foreach but it gives me error "Unhandled Rejection (TypeError): undefined is not iterable (cannot read property Symbol(Symbol.iterator))"

let BooksInfo=["Atomic Habit","Feel the Fear . . . and Do It Anyway","The Four Agreements"]

export default BooksInfo;

this is my first try :

import './App.css';
import Card from "./Card"
import Books from "./Books"
import { useEffect } from 'react';
import axios from "axios"
import { promised } from 'q';
function App() {
  useEffect( ()=>{
    
    async function test(){
      

        await Promise.all(Books.forEach( (book)=>{
        console.log(book + "👼👼🧔")
        const test1= axios.get(`https://openlibrary.org/search.json?q=${book}`)
        console.log(test1)
      }))
    }
    test()
    console.log("outside")
  })

I also tried this way but it still gives me the same error

import './App.css';
import Card from "./Card"
import Books from "./Books"
import { useEffect } from 'react';
import axios from "axios"
import { promised } from 'q';
function App() {
  useEffect( ()=>{
    
    async function test(){
      

      const test1= await Promise.all(Books.forEach( (book)=>{
        console.log(book + "👼👼🧔")
        axios.get(`https://openlibrary.org/search.json?q=${book}`)
        .then(res=>{
          console.log("helooo")
          console.log(res)
          // console.log(tes)
        })
      }))
    }
    test()
    console.log("outside")
  }) 

Solution

  • I'd suggest a better approach, with this you can easily catch errors if there were any while making an API call.

      try {
        const result = await Promise.all(BooksInfo.map( (book)=>{
          console.log(book + "👼👼🧔")
          const test1= axios.get(`https://openlibrary.org/search.json?q=${book}`)
          return test1; // This is essential; this is how map func works
        }))
    
        console.info("API Result", result);
      } catch (error) {
        console.error("Network error",error);
      }