0

I'm trying to add an object to an array using ReactJS on a button click. On the first click the array is returning empty in the console and I can't figure out why. It saves after the second click and second return of the array

const [favouriteBooks, setFavouriteBooks] = useState([]);
    
function addFavourite(event) {
    event.preventDefault();
    const favouritedBook = bookData[event.target.name];
    setFavouriteBooks((prev) => [...prev, favouritedBook]);
    console.log(favouriteBooks);
}

in after the first click the console outputs an empty array. I want to save the array as a JSON string in the local browser storage and when I tried that I was having the same issue.

Ezz
  • 7
  • 1

0 Answers0