I am facing a challenge with updating fields individually for an object named Post
. This object has three fields: title
, content
, and summary
.
Situation
To save a post in the database, I can fill in just the title
field initially and leave the other fields empty. The goal is to update these additional fields separately as needed when visiting the post page.
The code snippet on my page is used to update the title only
:
const updateTitleData = async () => {
try {
await fetch(`/api/story/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(title)
})
refreshData()
} catch (error) {
toast.error('Document could not be updated')
console.error(error);
}
};
Within the API route, the following code is implemented:
const storyId = req.query.id
const {title, content, summary} = req.body
else if (req.method !== 'PUT') {
console.log("Note could not be modified")
res.status(400).json({message: "Note could not be modified"})
} else {
await prisma.story.update({
where: {id: storyId},
data: {
title,
content,
summary
}
})
res.status(200).json({message: ' updated'})
}
My current setup seems to be ineffective as no mutation occurs when using this line of code: i.e
const {title, content, summary} = req.body
However, by changing it to individual assignment like this:
const title = req.body
const content = req.body
const summary = req.body
Updating any one field triggers a change, but it updates all fields with the same value. How can I achieve the goal of updating just one field at a time?