Reputation: 156
I am new to React + typescript and is trying to use "react-router-dom" to make a login component to communicate with my backend server.
Basically I am trying to make a class "Login" that, upon submitting a form, will trigger a fetch request to my server. If the response from my server is OK, I will then navigate to another page with the input data.
Everything works fine until I try to navigate to my second page. The thing is, I don't want the login credentials to appear in the url, and the rule of hooks is preventing me from using the navigate hook after checking the status code of my fetch response.
Does anyone have an idea about how I can achieve this? Any help would be appreciated.
Edit: added current code
interface MyProps{
}
interface MyStates{
username: string,
password: string
}
class Modal extends React.Component<MyProps, MyStates>{
constructor(props: MyProps){
super(props);
this.state = {username: '', password: ''};
this.handleUsernameChange = this.handleUsernameChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
this.handleLoginSubmit = this.handleLoginSubmit.bind(this);
}
handleUsernameChange(event: React.ChangeEvent<HTMLInputElement>) {
this.setState({username: event.target.value});
}
handlePasswordChange(event: React.ChangeEvent<HTMLInputElement>) {
this.setState({password: event.target.value});
}
handleLoginSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
var request = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: this.state.username, password: this.state.password})
}
fetch('login',request)
.then(response => {
if(!response.ok) throw new Error(response.statusText);
else {
// window.location.replace('/AfterLogin.html?name=' + this.state.username)
}
})
}
render(){
return <div className='Modal'>
<form onSubmit= { this.handleLoginSubmit }>
<label>
Username
<input type='text' name='username' value={this.state.username} onChange={this.handleUsernameChange} />
</label>
<p/>
<label>
Password
<input type='password' name='password' value={this.state.password} onChange={this.handlePasswordChange} />
</label>
<p/>
<button> Sign In</button>
</form>
</div>
}
}
Upvotes: 2
Views: 7316
Reputation: 331
You can use useNaviate()
hook from react router dom.
const navigation = useNavigate()
// OnLogin Successfully
navigation("/home",{state :{ name : "raeon"}, replace:true})
You need to pass two arguments. First one is link you want to navigate to. And in the second param you have to pass object with key, replace
and 'state`. React more about this on : https://reactrouter.com/docs/en/v6/api#usenavigate
Upvotes: 2