const [mekala, setMekala]= useState({posts:[]})
<button type="button" className="btn btn-warning" onClick{()=>deletePosts(post.id)}>DELETE</button>
const deletePosts= async (pid) => {
const { data } = await axios.delete(`${API}/${pid}`);
console.log(data);
}
whenever I perform deleteposts function, it is getting deleted on the server.
but to represent on UI, I need to do a filter function on the arrays.
How to bring the copy of states(mekala) here to write filter function so that I can again call setMekala to assign the deleted value to the state. To represent on UI.
CodePudding user response:
You should do like this:
const deletePosts= async (pid) => {
const {data}=await axios.delete(`${API}/${pid}`)
const filteredPost = data.post;
const filteredPostsList = mekala.posts.filter((post) => post.id !==
filteredPost.id);
setMekala({posts: filteredPostsList})
}
CodePudding user response:
This approach would result in fewer lines of code
const deletePosts = async (pid) => {
const { data } = await axios.delete(`${API}/${pid}`)
setMekala(prevState => prevState.posts.filter(post => post.id !== data.post.id))
}
And if you used it with React.useCallback
you would have one dependency less.
const deletePosts = React.useCallback(async (pid) => {
const { data } = await axios.delete(`${API}/${pid}`)
setMekala(prevState => prevState.posts.filter(post => post.id !== data.post.id))
}, []); // <--- no deps needed in this case
Read about "functional updates" with the React.useState hook here: https://reactjs.org/docs/hooks-reference.html#functional-updates