Home > Blockchain >  How to remove an item from list and add it to another list in Javascript?
How to remove an item from list and add it to another list in Javascript?

Time:05-03

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

CodePudding user response:

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

CodePudding user response:

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;
        });
    })
 }
  • Related