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

165
Vistas
How to remove an item from list and add it to another list in Javascript?

I'm trying to remove an item from a list and add the exact element to another list variable, but apparently it gets overwritten.

Here is the code :

const [data, setData] = useState(["fridge", "milk", "dog", "cryptocurrency", "school", "blockchain", "developer", "engineer", "minecraft", "prison", "scofield", "twelve" ])
const [result, setResult] = useState([])
let temp_result = []
const handleWord = (w) => {


    for (var i=data.length-1; i>=0; i--) {
        if (data[i] === w) {
            let element = data.splice(i, 1)
            setData([...data])
            temp_result.push(element[0])
            break;
        }
    }
    console.log(temp_result)
}

Please find attached an image of the console (temp_result) : at temp_result is empty, first button click I removed fridge from data and pushed it to temp_result, second button click I removed school from data and pushed it to temp_result, but the fridge element is gone.

enter image description here

How can I avoid this ? Thanks in advance !

P.S : when I declare temp_result outside of my export function of the component, it works just fine, is this a normal behavior in react native ?

full code :

  import {useState} from 'react'
  let temp_result = []
  export default function Passphrase({ navigation }) {
  const [data, setData] = useState(["fridge", "milk", "dog", "cryptocurrency", "school", "isychain", "developer","engineer", "minecraft", "prison", "scofield", "twelve" ])
const [result, setResult] = useState([])

const handleWord = (w) => {


    for (let i=data.length-1; i>=0; i--) {
        if (data[i] === w) {
            let element = data.splice(i, 1)
            setData([...data])
            temp_result.push(element[0])
            break;
        }
    }
   setResult(temp_result)
}
return (<View></View>)
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The issue is that you're not using the newest 'data' value when you do setData. [https://reactjs.org/docs/hooks-faq.html#why-am-i-seeing-stale-props-or-state-inside-my-function][1]

Replace setData([...data]) with setData(currentData => [...currentData, ...thingsToAdd])

This may be easier to read:

const [data, setData] = useState(["fridge", "milk", ...moreWords])

const handleWord = (wordToFind) => {
  const wordMatches = (word) => word === wordToFind;
  const indexOfWord = data.findIndex(wordMatches);

  if (indexOfWord) {
    setData(prev => {
      prev.filter(word => word === wordToFind); // remove the word
      return prev;
    }
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

While updating state properties in React, you need to use the callback argument on setters, due to the asynchronous nature of state updates.

https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

function handleWord(word) {
  setData((data)=> {
    return data.filter((w,i)=>{
      return w != word;
    });
  })
}

or shorthand:

const handleWord = (word) => setData(data => data.filter((w, i) => w !== word));
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