I am searching an array within my object to return an object with only the matched values in my categories array using filter & includes. For some reason whenever I try to run my function keep getting
TypeError: Cannot read property 'includes' of null
or
TypeError: false is not a function
if I use the find function within my filter.
What am I doing wrong?
[{
"entryTitle": "What Is Sports Medicine Acupuncture?",
"date": "September 30 2015",
"categories": ["Knee Pain"],
"type": false
}, {
"entryTitle": "Providing Quality Care During The COVID-19 Pandemic",
"date": "March 23 2020",
"categories": null,
"type": false
}, {
"entryTitle": "Correcting Severe Antalgic Posture & Gait",
"date": "May 09 2020",
"categories": ["Back Pain"],
"type": true
}, {
"entryTitle": "The Successful Treatment Of Sciatica And Low Back Pain With Sports Medicine Acupuncture®",
"date": "July 24 2020",
"categories": ["Back Pain"],
"type": true
}, {
"entryTitle": "Treating A Quad Strain For A Super Heavyweight Powerlifter Before The KERN US Open Powerlifting Meet",
"date": "June 28 2018",
"categories": ["Knee Pain"],
"type": true
}, {
"entryTitle": "Treating A High Hamstring Strain Before A Powerlifting Competition Using Sports Medicine Acupuncture®",
"date": "June 05 2020",
"categories": ["Back Pain"],
"type": true
}, {
"entryTitle": "Free Acupuncture Treatments For Veterans Through The Veterans Choice Program",
"date": "June 08 2017",
"categories": ["Back Pain", "Disc Herniation", "Shoulder Pain"],
"type": true
}, {
"entryTitle": "The Treatment Of Whiplash Related Injuries With Acupuncture",
"date": "March 04 2016",
"categories": ["Disc Herniation"],
"type": false
}]
My function
const [selected, setSelected] = useState("all")
const [posts, setPosts] = useState(postData)
const filterPosts = value => {
let posts = postData
if (value !== "all") {
posts = postData.filter(post => post.categories.includes(value))
//posts = postData.filter(post => post.categories.find(post.categories === value))
}
setSelected(value)
setPosts(posts)
}
Expected results
{
"entryTitle": "What Is Sports Medicine Acupuncture?",
"date": "September 30 2015",
"categories": ["Knee Pain"],
"type": false
},
{
"entryTitle": "Treating A Quad Strain For A Super Heavyweight Powerlifter Before The KERN US Open Powerlifting Meet",
"date": "June 28 2018",
"categories": ["Knee Pain"],
"type": true
},
This entry
{
"entryTitle": "Providing Quality Care During The COVID-19 Pandemic",
"date": "March 23 2020",
"categories": null,
"type": false
}
has categories
set to null. You can't do includes on it.
Fix it using optional chaining, or check the existence before:
post.categories?.includes(value)
or
post.categories && post.categories.includes(value)