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

420
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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