Home > Back-end >  React js Combining 2 arrays to make a new array of objects using spread and state
React js Combining 2 arrays to make a new array of objects using spread and state

Time:10-31

I'm new in react and js and I'm attempting to create an array from a declared array of json objects and a second array from user inputs. The idea is I have a list of objects existing, and the user can add to this list as many items as they like. My problem is I can only currently add one more item to my list, and subsequent items over write it. I believe my issue lies in the line:

let newBooks = [{title, author, rating}]

but I'm having trouble correcting it. Any help is appreciated. Cheers.

 const addBookToList = () => {
    let newBooks = [{title, author, rating}]
    const allBooks = [...FAVOURITE_BOOKS, ...newBooks]
    setBooks(allBooks)

    setTitle("")
    setAuthor("")
    setRating("")
  }

For reference, everything I'm working on is within index.js

CodePudding user response:

Use an updater function which "takes the pending state and calculates the next state from it". Here prev is the pending state, and we spread that out into a new array, and add the new book to it.

const { useEffect, useState } = React;

function Example({ favouriteBooks }) {

  const [title, setTitle] = useState('My book');
  const [author, setAuthor] = useState('Mr. Smith');
  const [rating, setRating] = useState(2);
 
  const [books, setBooks] = useState(favouriteBooks);

  function addBookToList() {
    const book = { title, author, rating };
    setBooks(prev => [ ...prev, book ]);
  }

  useEffect(() => console.log(books), [books]);

  return (
    <div>
      <button onClick={addBookToList}>
        Add book to list
      </button>
    </div>
  );

}

const favouriteBooks=[{title:"Harry Potter and the Philosopher's Stone",author:"J.K. Rowling",rating:9},{title:"The Great Gatsby",author:"F. Scott Fitzgerald",rating:8}];

ReactDOM.render(
  <Example favouriteBooks={favouriteBooks} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

CodePudding user response:

You need to keep the objects in current state as well, probably like

const App = () => {
  const [books, setBooks] = useState(FAVORITE_BOOKS);

  const addBook = () => {
    const newBook = ...
    // append
    setBooks(b => [...b, newBook];
  };
};
  • Related