Here is the request section of code that is causing the error, I'm making a patch request via Postman and it successfully updates the array of objects that I want
app.patch('/comments/:id', (req, res) => {
const { id } = req.params;
const foundComment = comments.find(c => c.id === id)
const newCommentText = req.body.comment;
foundComment.comment = newCommentText; //THIS LINE IS THE ONE FLARING THE TYPE ERROR
//CANNOT SET PROPERTIES OF UNDEFINED (setting 'comment')
res.redirect('comments')
})
My thought process for how the above code works or I think it should?
app.patch('/comments/:id', (req, res) => { //Defines logic for what should happen when a patch request is // made @/comments/:id
// Then the ID is taken out of the request object that the user inputs and is stored in a variable id // Then I created a foundComment variable to store an object taken from an array using the array.find // method to identify the correct object.
The foundComment.comment = newCommentText is where the type error TypeError: Cannot set properties of undefined (setting 'comment' appears.
Or
TypeError: Cannot set properties of undefined (setting 'comment')
// but as far as I'm aware this should take the comment from form data parsed in (I have done app.use(express.urlencoded({extended: true}) ) and modify this data
the res.redirect was intentional only for when I made an EJS template to fulfil this task on, I understand its use is moot at the moment, I Just cannot fathom how I'm getting the error
This is the array for reference:
> const comments = [
> {name: 'Boris',
> comment: 'Hahaha Nice One Dude',
> id: uuidv4()
> },
> {name: 'Dan',
> comment: 'That triangle was nuts',
> id: uuidv4()
> },
> {name: 'James',
> comment: 'Sorry I broke your knee',
> id: uuidv4()
> }
> ]
I haven't produced a form for it yet as this part of the online course I'm doing doesn't do so
I've narrowed the problem down to being that while the code actually succeeds in making the post request, I seem to be getting the error due to the foundComment.comment line as it states that the method cannot be used as foundComment is undefined, which confuses me as I've defined it prior to be equal to,
const foundComment = comments.find(c => c.id === id)
I thought it might be an issue with comments.find but after using it standalone I can confirm it returns the correct object and stores it in foundComment.
I also console.logged all ids, because my ids are generated using UUID, I print them out everytime I run the code on node so I can confirm that when i'm making a patch request the id for which I'm trying to update does indeed exist!
When I hover over found comment the following shows, I'm not sure why there is | undefined is there but this is as far as I've gotten.
const foundComment: {
name: string;
comment: string;
id: string;
} | undefined