Home > Back-end >  updating data in useState constant | React
updating data in useState constant | React

Time:02-24

I'm trying to make "load more" pagination in react app fetching data from google books api via axios. Firstly I'm grabbing data by submitting the form and setting it into the bookResponse const and then putting the value of bookResponse const into the booksArray const by setBooksArray(bookReponse). Secondly I need to show more book's by clicking the 'Load More' button. By click I make a new request to the api and receive the response. I'm updating the bookResponse const with new data and trying to update the booksArray const by setBooksArray(booksArray bookResponce) but it returns errror "books.map is not a function". How can i solve the problem?

{books && books.map(book => (
        <div key={book.id}>
            <img alt="book's thumbnail" src={book.volumeInfo.imageLinks.thumbnail} />
            <div>
                <h5>{book.volumeInfo.title}</h5>
                <p>{book.volumeInfo.authors}</p>
                <p>{book.volumeInfo.categories}</p>
            </div>
        </div>
    ))
    }
function App() {
  const [bookName, setBookName] = useState('')
  const [bookCategory, setBookCategory] = useState('all')
  const [bookFilter, setBookFilter] = useState('relevance')
  const [bookResponse, setBookResponse] = useState([])
  const [booksArray, setBooksArray] = useState([])
  const apiKey = ('MY_KEY')
  const [showLoadMoreButton, setShowLoadMoreButton] = useState(false)

  const handleSubmit = (e) => {
    e.preventDefault()
    console.log(bookName, bookCategory, bookFilter)

    axios.get(endpoint)
    .then(res => {
        console.log(res.data.items)
        setBookResponse(res.data.items)
        setBooksArray(bookResponse)
        console.log(bookResponse ,booksArray)
    })
    setShowLoadMoreButton(true)
  }
  const handleLoadMore = (e) => {
    e.preventDefault()

    axios.get(endpoint)
    .then(res => {
        console.log(res.data.items)
        console.log(bookResponse)
        setBookResponse(bookResponse)
        setBooksArray(booksArray   bookResponse)
    })
  }

CodePudding user response:

You don't to add 2 arrays, you can do something like this.

setBooksArray( prev => [ ...prev, ...bookResponse ] )
....
return (
      ....
      { booksArray.map(book => ( .....) }
      .....
)

CodePudding user response:

if booksArray and bookResponse types are array you can use this:

setBooksArray([...booksArray,...bookResponse])
  • Related