Khan Faizan
Khan Faizan

Reputation: 93

How To Redirect To Another page in React js

I Want To redirect To List Page of My Application From App Component After Saving Data ... history.push("/List") not Working... Below Is my Code.. Please Help.

let history= useHistory();
 let SaveData=(props)=>{
 
    fetch('https://localhost:44345/api/Student/Save', {
      method: 'post',
      headers: {'Authorization': 'Basic ' + btoa('admin:admin'),'Content-Type':'application/json'},
      body: JSON.stringify({
       "Name": props.name,
       "Age": props.age,
       "Gender": props.gender
       
      })
     }).then(function(response) {
      console.log(response.status);       
      if (response.ok) {
        alert('Data Saved succesfully');
        redirect();
      }
  })
  }

  function redirect() {
    history.push("/List")
  }

Upvotes: 0

Views: 1614

Answers (1)

Vladimir Trotsenko
Vladimir Trotsenko

Reputation: 246

You can use useNavigate from React-Router-Dom v6.

import { useNavigate } from "react-router-dom";

export default App() {
  const navigate = useNavigate()
  ...
  if (response.ok) {
    navigate('/list')
  }
}

Upvotes: 1

Related Questions