-
-
Save siumhossain/d158dac491d17ca41a540ae57279460d to your computer and use it in GitHub Desktop.
update specific portion of array after submitting post request in next js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const submitComment = async (e, id) => { | |
e.preventDefault(); | |
const data = { | |
comment: commentData, | |
article: id | |
} | |
await axios.post(`${process.env.NEXT_PUBLIC_ROOT_URL}/api/v1/article_comment/`, data, { | |
headers: { Authorization: `Token ${token}` }, | |
}) | |
.then(res => { | |
console.log(res.data) | |
setData(prevData => ({ | |
...prevData, | |
comment: [...prevData.comment, res.data] | |
})); | |
}) | |
.catch(err => { | |
console.log(err) | |
}) | |
console.log(commentData) | |
setCommentData(''); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// if want to updated nested field | |
async function submit_reply(e, id, index) { | |
const input_data = { | |
comment: id, | |
reply: reply | |
} | |
await axios.post(`${process.env.NEXT_PUBLIC_ROOT_URL}/api/v1/article_reply/`, input_data, { | |
headers: { Authorization: `Token ${token}` }, | |
}) | |
.then(res => { | |
console.log(res) | |
setData(prevData => { | |
const updatedReplies = [...prevData.comment[index].reply, res.data]; | |
const updatedComment = { ...prevData.comment[index], reply: updatedReplies }; | |
const updatedComments = [...prevData.comment]; | |
updatedComments[index] = updatedComment; | |
return { | |
...prevData, | |
comment: updatedComments | |
}; | |
}); | |
console.log('comment', data?.comment[index]) | |
}) | |
.catch(err => { | |
console.log(err) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment