Route component does not render - React

Asked

Viewed 467 times

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

  • Unfortunately not.

1 answer

0

I had a problem like that once and I don’t really remember much of the problem at the time, but it was related to the Sagas when they needed to change routes. My solution was to use the Connected React Router.

Take a look there at the current documentation, but when I did it was like this:

In your Store:

import { createStore, compose, applyMiddleware } from "redux";
import createSagaMiddleware from "redux-saga";
import { routerMiddleware } from "connected-react-router";

import history from "../routes/history"; // Atenção ao caminho
import sagas from "./sagas";
import reducers from "./ducks"; // Eu usava o Duck pattern

const sagaMonitor =
  process.env.NODE_ENV === "development"
    ? console.tron.createSagaMonitor()
    : null;
const sagaMiddleware = createSagaMiddleware({ sagaMonitor });

const middlewares = [sagaMiddleware, routerMiddleware(history)];

const createAppropriateStore =
  process.env.NODE_ENV === "development"
    ? console.tron.createStore
    : createStore;

const store = createAppropriateStore(
  reducers(history),
  compose(applyMiddleware(...middlewares))
);

sagaMiddleware.run(sagas);

export default store;

In the index of the combineReducer:

import { combineReducers } from "redux";
import { connectRouter } from "connected-react-router";
... // seus reducers e outras coisas

export default history =>
  combineReducers({
    router: connectRouter(history),
    auth,
... // seus reducers
)}

And ai in Saga, instead of using history, uses the push function of the Connected React Router:

...
import { push } from "connected-react-router";

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));

      yield put(push('/dashboard')); // Aqui no lugar de history.push

   }
   catch (error) {
      console.log('Erro na autenticação');
   }
};
  • I tried a lot of times here, I did it by the code you showed, I looked at the link you sent, I did it the way I taught there, I saw a video of the rocketseat about it, I tried tbm, but nothing I did worked. Damn route component still not rendering without me having to reload.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.