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

295
Views
How to delete a specific item from localstorage in react redux

How can I remove a specific item (by id) from localstorage using react (redux - persist)? handleSubmit is working fine, but handleDelete, is not. I have this:

 handleSubmit = event => {
    event.preventDefault();
    this.props.addWeather(this.state.weatherCity);
    this.setState({ weatherCity: "" });
  };

handleDelete = (event, id) => {
    this.props.deleteWeather(this.state.weatherCity);
    this.setState({ weatherCity: "" });
  }

const mapStateToProps = state => ({
      allWeather: state.allWeather
    });
    
    const mapDispatchToProps = dispatch =>
      bindActionCreators(WeatherActions, dispatch);
    
    export default connect(mapStateToProps, mapDispatchToProps)(WeatherList);

And button in form to call handleDelete:

<form onSubmit={this.handleDelete}><button type="submit" id="add" onClick={this.handleDelete}>Remove City</button></form>

My localstorage:

allWeather: "[{\"id\":0.5927975642362653,\"city\":\"Toronto\"},{\"id\":0.8124764603718682,\"city\":\"Fortaleza\"},{\"id\":0.9699736666575081,\"city\":\"Porto\"},{\"id\":0.852871998478355,\"city\":\"Tokio\"},{\"id\":0.8854642571682461,\"city\":\"New York\"}]"

My reducer:

export default function allWeather(state = [], action) {
  switch (action.type) {
    case "ADD_WEATHER":
      return [...state, { id: Math.random(), city: action.payload.city }];
    case "DELETE_ITEM":
      return [...state, state.weatherCity.filter((event, id) => id !== action.payload.id)];
    default:
      return state;
  }
}

And actions:

export const deleteWeather = id => ({
  type: "DELETE_ITEM",
  payload: { id }
});

I appreciate any help.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your problem is that you are using the spread operator, which copies the content of the current state first. Then you are adding the items that were returned from the filter method. So you aren't deleting but adding. To delete from an array use the filter method only, without the spread operator like that:

return state.filter( (city) => city.id !== action.payload.id )

Also the state is an array, not an object, so this is invalid state.weatherCity.

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!