Does anyone here help me to to convert this IF condition into .filter method?
Hello there.
For future posts, please do not paste screenshots of code. This is not easy to work with, and you are much less likely to get helped.
Sorry .
can i write this code in a different way?
onBookShelfChange = (e) => {
const shelf = e.target.value;
this.props.onShelfChange(this.props.book, shelf);
};
Assuming that searchResults is a list of books, I think what you are trying to do is something like this:
searchResults = searchResults.filter(book => book.shelf === this.props.books.find(b => b.id === book.id).shelf);
Thanks and what about this one ?I also want this one to change into .filter.
onShelfChange = (book, shelf) => {
BooksAPI.update(book, shelf).then(
this.setState((state) => ({
books: state.books.map((b) => {
if (b.title === book.title) {
b.shelf = shelf;
return b;
} else {
return b;
}
}),
loading: false,
}))
);
};
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>
) will also add backticks around text.
Note: Backticks are not single quotes.
Alright ,thanks for informing.
This a weird way of writing React to be honest, anyways, an update method usually works as follow:
- You pass as a parameters the elements you want to update
- Find the element you passed as parameter in your list of elements, in this case in your list of books you find the book you passed as a parameter.
- Once the element is found, you update its values.
Now you need to think how to do it in React. Your list of books is in your state
object.