Reputation: 772
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.
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>)
Upvotes: 0
Views: 474
Reputation: 363
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;
}
}
}
Upvotes: 2
Reputation: 1861
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));
Upvotes: 1