After performing a fetch and receiving a successful response containing data as an object, I use router.push
to redirect the page to another one where I want to display the fetched data.
const handleSubmit = async (event: any) => {
event.preventDefault();
try {
const response = await fetch('http://localhost:8080/api/auth/signin', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
});
const responseData = await response.json();
if (responseData) {
console.log('Login successful!', responseData);
localStorage.setItem('accessToken', responseData.token);
localStorage.setItem('username', responseData.username);
toast({
description: "Login successful"
});
router.push({
pathname: '/',
query: responseData
});
setFormData({
username: '',
password: ''
});
} else {
// If the response is not as expected
console.error('Unexpected API response:', responseData);
setError('Invalid credentials. Please try again.');
}
} catch (error) {
console.error('Error during login:', error);
}
};
I'm encountering errors with the router.push
, but how can you effectively pass a response between different pages?