Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

364
Visualizações
Array.push() function not working in React JS

I have an object which represents a recipe, whenever I click the "Add" button my function is supposed to add that corresponding recipe to an empty object array, but oddly only on recipe object gets added to the empty array and when i try to add more than one then it throw this at me: favList.push is not a function.

My HTML Code:


import React from 'react'
import './home.css'

const Home = (props) => {
return <div className="home">
               
                     <div className="wrapper">
                            {props.items.map((item) => {
                                  return  <div className="flexIt">
                                                    {item.ingredients.map((ingredient) => 
                                                        <ol>
                                                            <li>{ingredient}</li>
                                                        </ol>
                                                    )}        
                                                </div>
                                            </div>
                                            <div className="closeBtn">
                                                <button onClick = {() => {props.onRemove(item)}} >X</button>
                                                <button onClick = {() => {props.addItemToFav(item)}} >Add</button>
                                            </div>
                                          </div>})}
                            </div>
                     </div> 
                </div>
            </div>
}

export default Home

My JavaScriipt code:


import './App.css';
import Home from './components/Home';
import AddRecipe from './components/AddRecipe';
import { useNavigate } from 'react-router'
import items from './data';
import React, { useState } from 'react';
import {Routes, Route} from 'react-router-dom';

    const App = () => {
    const navigate = useNavigate(); 
    const [favList, setFavList] = useState([]);
    
  const addToFav = (itemToBeAdded) => {
      setFavList(favList.push([itemToBeAdded]));
      console.log(favList);   
  }
  return (

      <Routes>
        <Route exact path="/" element={<Home onRemove={removeItem} addItemToFav={addToFav} items={itemsList}/>} />
        <Route path="/addRecipe" element={<AddRecipe onAddRecipe={(newRecipe) => {
        addRecipe(newRecipe);
        navigate('/');
      }}
    />} />
        </Routes>
  );
}

export default App;

***
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First, push will mutate the existing array.

Then you pass the return value to setFavList (which is a number representing the length of the array).

You need to pass a new array to setFavList. You can't (usefully) pass that number or the original (but mutated) array (since it would detect it is the same array and do nothing).

For example:

const addToFav = (itemToBeAdded) => {
  const replacementList = [...favList, itemToBeAdded];
  setFavList(replacementList);
}

(Note also that itemToBeAdded probably shouldn't be wrapped in an extra array.)

Then your attempt to log the new value needs to be moved because addToFav will have closed over the original value. This is explained by answers to this question

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda