Answer the question
In order to leave comments, you need to log in
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
this.setState({
comments: comments.filter(
(comment, i) => {
return i !== index;
},
() => localStorage.setItem("state", JSON.stringify(this.state))
)
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question