S
S
Sergey2019-11-24 21:07:24
React
Sergey, 2019-11-24 21:07:24

How to remove comment from localstorage in React?

Tell me how to remove a comment from localStorage along with removal from the general list (removeComment function)?

import React, { Component } from "react";
import CommentSection from "./CommentSection";
import Form from "./Form";

class App extends Component {
  state = {
    comments: []
  };

  componentDidMount() {
    if (localStorage.getItem("state")) {
      this.setState({ ...JSON.parse(localStorage.getItem("state")) });
    }
  }

  //Добавление комментария
  handleSubmit = comment => {
    this.setState({ comments: [...this.state.comments, comment] }, () =>
      localStorage.setItem("state", JSON.stringify(this.state))
    );
  };

  //Удаление комментария
  removeComment = index => {
    const { comments } = this.state;

    this.setState({
      comments: comments.filter(
        (comment, i) => {
          return i !== index;
        },
        () => localStorage.setItem("state", JSON.stringify(this.state))
      )
    });
  };

  render() {
    const { comments } = this.state;

    return (
      <div className="container">
        <Form handleSubmit={this.handleSubmit} />
        <CommentSection
          commentData={comments}
          removeComment={this.removeComment}
        />
      </div>
    );
  }
}

export default App;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-11-24
@SerGeGR

this.setState({
  comments: comments.filter(
    (comment, i) => {
      return i !== index;
    },
    () => localStorage.setItem("state", JSON.stringify(this.state))
  )
});

Indeed, the second parameter is filter, the second parameter is setState - the difference is small, essentially the same thing, it should work as it should. Or is it still not?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question