Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

419
Vistas
How to remove items from a list in React Function Component

I am trying to remove object from a list in react but have no luck. I'm using react hook to maintain state:

const [temp, setTemp] = useState([]);
 useEffect(() => {
    call service().then(response => {
      let list = response.data.list // [{name:"test"}, {name:"xyz"}]
      setTemp(list); // empty
      handleRemove(name);
      console.log(temp) // empty
  }, []);
  
  
  function handleRemove(name) {
    const newList = temp.filter((item) => item.name !== name);
    console.log("remain lane--"+newList)
    setTemp(newList);
  }

I don't know what's happing but it is not setting the temp list. I tried multiple ways to remove element from the list.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

React useState is Async operation and you can not see the update immediately.

Actually your code works fine but you can't see it!. To see the changes that made to the state I changed the code as below:

React.useEffect(() => {
  setTemp(list);
}, []);

React.useEffect(() => {
  console.log(temp);
}, [temp]);

function handleRemove(s_name) {
  const newList = temp.filter((item) => item.name !== s_name);
  //console.log("remain lane--"+newList);
  setTemp(newList);
}

return (
  <div>
    <button
      onClick={() => {
        handleRemove("blue");
      }}
    >
      Remove 'blue'
    </button>
  </div>
);

I put the handleRemove function in a button click event to perform this action in different time as you click on it.

Please see the updated code in CodeSandBox: Here is the CodeSandbox: CodeSandbox

about 4 years ago · Juan Pablo Isaza Denunciar

0

In handleRemove you have to use temp.filter instead of list.filter

list isn't in the scope of the useEffect so handleRemove can't access it, but temp can be accessed since it's in the scope above the useEffect and handleRemove.
So once you've fetched the data and assigned it to temp

list = temp

function handleRemove(name) {
    const newList = temp.filter((item) => item.name !== name);
    console.log("remain lane--"+newList)
    setTemp(newList);
  }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda