0

I want to update my state in foreach but when I check, It just keeps the last one and it doesn't keep previous data.

import './App.css';
import Card from "./Card"
import Books from "./Books"
import { useEffect, useState } from 'react';
import axios from "axios"
import BooksInfo from './Books';
function App() {
  const [bookInfo,setBookInfo] = useState([])
  useEffect( ()=>{
    let bname = ""
    let bauthor = ""
    let bcover = 0
    async function getInfo(){
        let results = Promise.all(BooksInfo.map(book=>{
          let result = axios.get(`https://openlibrary.org/search.json?q=${book}`)
          return result
        }))
        ;(await results).forEach(result=>{
          console.log(result)
            bname= result.data.docs[0].title_suggest
            bauthor= result.data.docs[0].author_name[0]
            bcover= result.data.docs[0].cover_i
            setBookInfo([...bookInfo , { name:bname , author:bauthor  , cover:bcover }]);
            console.log(bookInfo)
        })
    }

    getInfo()
  },[])  
skyboyer
  • 22,209
  • 7
  • 57
  • 64
  • 1
    why dont you just save it all to a variable and the set the state when the foreach is done? – Richard Hpa Jun 29 '21 at 01:09
  • Shouldn't `bookInfo` be an **array** of objects, not a single object? You're fetching data for multiple books, yet only have only book object in state - how are you gonna store them all? – Jayce444 Jun 29 '21 at 01:12
  • @Jayce444 you are right I updated my code but it still keeps the last one. – Yasaman Forouzesh Jun 29 '21 at 01:28
  • @RichardHpa Thanks for your suggestion but I want to learn this way to see how foreach and state can work together. – Yasaman Forouzesh Jun 29 '21 at 01:29
  • Why don't you simply call `setBookInfo` only once, with `bookInfo.concat(newBookInfo)`? Much more efficient. – Bergi Jun 29 '21 at 01:31
  • Doing it this way will result in a lot of unnecessary re-renders and any UI based on bookInfo will be constantly changing while the state keeps changing. I really think you should get all the info together and then set it to state once. – Richard Hpa Jun 29 '21 at 01:33

0 Answers0