Reputation: 145
Everything is working fine.
The problem is when I press the delete button, it deletes but not immediately from table. It deletes when I reload the page. I replace the student array in localStorage when I press delete. Your help will be appreciated. Thank you in advance.
const history = useHistory();
let student = JSON.parse(localStorage.getItem('student'))
This is the function for the deletion of an item
const deleteStudent = (event)=>{
let id = event.currentTarget.id
let students = student.map(student=>Number(student.id))
let index = students.indexOf(Number(id))
student.splice(index,1)
localStorage.setItem('student',JSON.stringify(student))
}
Upvotes: 0
Views: 210
Reputation: 931
You can use useEffect()
hook for re rendering the component. You can set the dependency when it should render. I am not sure about the use case for local storage here but you can use useState()
hook to update the data and render the component or you can use the useEffect()
hook by adding the dependencies and render the component.
Link for the useEffect hook - https://reactjs.org/docs/hooks-effect.html
Link for the useState hook - https://reactjs.org/docs/hooks-state.html
//declare this in the start of the component
const studentsData = JSON.parse(localStorage.getItem('student'))
const [students, setStudents] = useState(studentsData);
const deleteStudent = (event)=>{
let id = event.currentTarget.id
let studentIds = students.map(student=>Number(student.id))
let index = studentIds.indexOf(Number(id))
students.splice(index,1)
localStorage.setItem('student',JSON.stringify(student))
}
useEffect(() => {
setStudents(JSON.parse(localStorage.getItem('student')))
}, [localStorage.getItem('student')]);
Upvotes: 1