React history.push() is updating url but not navigating to dashboard page in browser #521
Description
[App.tsx ]
import { BrowserRouter as Router, Route, Routes, Navigate} from 'react-router-dom';
import { Provider } from 'react-redux';
import store from './store/store';
import SignupForm from './pages/signup/signup';
import LoginForm from './pages/login/login';
import Dashboard from './pages/dashboard/dashboard';
import './App.css';
export const App = () => {
return (
<Route path="/" element={} />
<Route path="/signup" element={} />
<Route path="/login" element={} />
<Route path="/dashboard" element={} />
);
}
[login.tsx]
import React, { FormEvent, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { login } from '../../store/slices/login';
import InputField from '../../components/InputField';
import Form from '../../components/Form';
import FormRow from '../../components/FormRow';
import FormLeft from '../../components/FormLeft';
type LoginFormState = {
email: string;
password: string;
};
const LoginPage = () => {
const navigate = useNavigate();
const dispatch = useDispatch();
const [localData, setLocalData] = useState({ email: '', password: '' });
const { error, successMessage } = useSelector((state: any) => state.login);
const handleSubmit = (event: FormEvent) => {
event.preventDefault();
dispatch(login(localData));
};
const handleInputChange = (event: React.ChangeEvent) => {
setLocalData({ ...localData, [event.target.name]: event.target.value });
};
const handleLoginButtonClick = () => {
navigate('/signup');
};
return (
LOGIN FORM
Your Email
Password
{error &&
{successMessage &&
Login
);
};
export default LoginPage;
[loginSaga.tsx]
import { takeLatest, call, put } from 'redux-saga/effects';
import { PayloadAction } from '@reduxjs/toolkit';
import { login, loginSuccess, loginFailure } from '../store/slices/login';
import history from '../helpers/history';
type LoginFormState = {
email: string;
password: string;
};
function* handleLogin(action: PayloadAction) {
const url = process.env.REACT_APP_API_URL! + "users/login";
try {
const response: Response = yield call(fetch, url, {
method: 'POST',
mode:"cors",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(action.payload)
});
const data: { success: boolean; data:{token:string,message:string}; message?: string } = yield call([response, 'json']);
if (data.success && data.data.token) {
localStorage.setItem('token', data.data.token);
yield put(loginSuccess({ token: data.data.token }));
history.push('/dashboard');
} else {
yield put(loginFailure({ error: data.message || 'An unknown error occurred' }));
}
} catch (error) {
if (error instanceof Error) {
yield put(loginFailure({ error: error.message }));
} else {
yield put(loginFailure({ error: 'An unknown error occurred' }));
}
}
}
export function* loginSaga() {
yield takeLatest(login.type, handleLogin);
}