0

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))
}

1 Answer 1

1

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')]);
Sign up to request clarification or add additional context in comments.

2 Comments

how do I implement it? can you kindly write the code for that program? or do I have to just put this?
Edited my code. This way you can handle. If you dont need to store in the local storage you can use useState hook for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.