Home > Enterprise >  JS Filter is not filtering out element from array of objects based on !== conditional
JS Filter is not filtering out element from array of objects based on !== conditional

Time:07-07

Not sure what I am doing wrong here - it could be to do with how I am using useEffect() but I'm not clear on how to fix it. Essentially, I am running .filter over an array of objects and trying to make a filtered array that DOES NOT include a specific element from the array. I am quite new to using React and useEffect() in particular so think the trouble might come from there?

Here is the data:

[
{
author: 2
blurb: lorem ipsum
book_id: 2
cover_image: x
genre: "Literary Fiction"
id: 2
pub_year: 2020
title: "Shuggie Bain"
},

{
author: 2
blurb:  lorem ipsum
book_id: 14
cover_image: x
genre: "Literary Fiction"
id: 14
pub_year: 2022
title: "Young Mungo"
}
]

Here is the code:


export default function BookPage() {
  let { bookId } = useParams()
  const [bookInfo, setbookInfo] = useState({})
  const [booksByAuthor, setBooksByAuthor] = useState([{}])

  useEffect(() => {
    api
      .getBookById(bookId)
      .then((bookInfo) => {
        setbookInfo(bookInfo)
        api.getBooksByAuthor(bookInfo.author_id).then((books) => { //data above
          setBooksByAuthor(books)
          return null
        })
      })
      .catch((err) => {
        console.log(err)
      })
  }, [bookId])

  const otherBooks = booksByAuthor.filter((obj) => {
    return obj.book_id !== bookId
  })

[...]

This returns the same array as above, so isn't filtering out the value that matches the condition.

CodePudding user response:

Maybe book id is a string and obj.book_id is a number?

CodePudding user response:

this usually happens because the useState takes milliseconds to update, it is better to perform the filter in the same function and then give the final value to the state

      api
      .getBookById(bookId)
      .then((data) => {
        setbookInfo(data)
        api.getBooksByAuthor(data.author_id).then((books) => { //data above
          const newArray = books.filter(obj => obj.book_id !== bookId);
          setBooksByAuthor(newArray)
      })
      .catch((err) => {
        console.log(err)
      })

Also note that your "bookInfo" variable is repeated, this is not recommended.

  • Related