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.
CodePudding user response:
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);
}
CodePudding user response:
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