I have a process where the comments associated to a book record are stored in an array in a state and has actions to POST or DELETE an individual record and array element. I have the POST action working as intended and the DELETE API call working to delete my record from a database, but I'm not sure the best practice to search my array for the newly deleted record and to remove that value from the array or if I should trigger a refresh method for the React component to display the newly changed array.
Parent state and functionality (question is related to deleteCommentsFunc()
:
class BookFeed extends React.Component {
constructor(props){
super(props);
this.state = {
comments: []
};
this.deleteCommentsFunc = this.deleteCommentsFunc.bind(this);
}
componentWillReceiveProps(nextProps){
console.log("componentWillReceiveProps");
console.log(nextProps);
let commentArr = [];
nextProps.books.map((book) => {
book.book_comments.map((comment) => {
commentArr.push(comment);
})
})
console.log(commentArr)
this.setState({comments: commentArr});
}
deleteCommentsFunc(deletedComment){
console.log(deletedComment);
var updatedCommentArr = this.state.comments;
var index = updatedCommentArr.indexOf(deletedComment.target.value);
updatedCommentArr.splice(index, 1);
this.setState({comments: updatedCommentArr});
}
render(){
return (
<div>
{
this.props.books.map((book, index) => {
return (
<div className="row">
<div className="col-md-6 col-md-offset-3 book-card-container">
<BookCard {...book} key={book.bookIdHash} user={this.props.user} />
<Comments comments={this.state.comments} key={index} bookId={book.bookIdHash} csrf={this.props.csrf} updateComments={this.updateCommentsFunc} deleteCommentFunc={this.deleteCommentsFunc} user={this.props.user.userId}/>
</div>
</div>
);
})
}
</div>
);
}
}
Child function calling DELETE and passing returned JSON (which is just a 1 indicating a successful delete):
deleteCommentCall(bookId, bookCommentId, csrf){
var body = { bookId: bookId, bookCommentId: bookCommentId };
var route = 'http://localhost:3000/app/book/' + bookId + '/comment/' + bookCommentId;
fetch(route,
{
method: 'DELETE',
body: JSON.stringify(body),
headers: {
'X-CSRF-Token': csrf,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => {
return res.json();
})
.then(data => {
console.log(data);
this.props.deleteCommentFunc(data)
this.setState({'flash': 'success'});
})
.catch(err => {
console.log(err);
this.setState({'flash': 'error'});
});
}
As you might be able to tell the parameter value data
, which contains a 1 if DELETE was successful is not helpful in my deleteCommentsFunc()
, and what I really need to have is a value that I can find within the array to be able to remove it.