Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

422
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!