0
I’m having trouble rendering the component when I navigate between routes using history. It turns out that simply the route component is not rendered when I give a history.push('/path').
The url changes, but nothing appears on the screen. I need to reload the component page to be rendered.
Here is the code: index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
App.js
import React from 'react';
import Routes from './routes';
import { Router } from 'react-router-dom';
import { Provider } from 'react-redux';
import history from './services/history';
import store from './store';
function App() {
return (
<Provider store={store}>
<Router history={history}>
<Routes />
</Router>
</Provider>
);
}
export default App;
Routes: index.js
import React from 'react';
import { Switch } from 'react-router-dom';
import Route from './Route';
import Login from '../pages/Login';
import Dashboard from '../pages/Dashboard';
export default function Routes() {
return (
<Switch>
<Route path="/" exact component={Login}/>
<Route path='/dashboard' component={Dashboard} isPrivate />
</Switch>
);
}
Routes: Route.js (to control who is logged in or not)
import React from 'react'
import { Route, Redirect } from 'react-router-dom';
import store from '../store';
export default function RouteWrapper({
component: Component,
isPrivate = false,
...rest
}) {
const { logged } = store.getState().auth;
if (!logged && isPrivate) {
return <Redirect to="/"/>;
}
if (logged && !isPrivate) {
return <Redirect to="/dashboard" />;
}
return <Route {...rest} component={Component} />;
};
history js.
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
saga of authentication:
export function* login({ payload }) {
try {
const { username, ppassword } = payload;
const response = yield call(api.post, 'auth', {
username,
ppassword
});
const { user, token } = response.data;
yield put(loginSuccess(user, token));
history.push('/dashboard');
}
catch (error) {
console.log('Erro na autenticação');
}
};
I log in, but on the Dashboard page, nothing is shown until I reload the page.
Could you tell me where the problem is?
Thank you.
Did you solve the problem? I’m with an equal
– guilherme
Unfortunately not.
– Gabriel Otto