I am trying to navigate to Main page once authentication is successful, I am using redux-saga for making API calls. Below is my login generator function:
import * as Type from '../actions/types';
import { takeLatest, put, call } from 'redux-saga/effects';
import firebase from 'firebase';
import { push } from 'react-router-redux';
function* loginUser(action) {
const auth = firebase.auth();
try{
console.log(action.user);
const result = yield call([auth, auth.signInWithEmailAndPassword], action.user.email, action.user.password);
console.log('login sucess');
yield put({type: Type.AUTH_SUCCESSFULL, user: action.user, authMessage:'Login Success'});
console.log('done'); //being logged
yield put(push('/home')); /not being redirected to home. Even the browser url is not changing
console.log('pushed'); //being logged
}
catch(error){
console.log(error.message);
yield put({type: Type.AUTH_FAILED, errorMessage: error.message});
}
}
I just installed react-router-redux and tried doing this, Can someone please tell me what I am doing wrong?
I faced the same issue and following is my solution. Code you have added has not an issue. You need do some extra works to make this work.
Reducer.js
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';
import { History } from 'history'
const redusers = {
...
}
const mainReducer = (history: History) => combineReducers({
router: connectRouter(history),
...redusers
})
export default mainReducer;
Store.js
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import logger from 'redux-logger';
import { createBrowserHistory } from 'history'
import { routerMiddleware } from 'connected-react-router'
import mainReducer from './mainReducer';
import rootSaga from './rootSaga';
export const history = createBrowserHistory()
const configureStore = (preloadedState?: any) => {
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
mainReducer(history),
preloadedState,
applyMiddleware(routerMiddleware(history), logger, sagaMiddleware),
);
sagaMiddleware.run(rootSaga);
return store;
};
export default configureStore;
index.js
import React, { Suspense } from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import * as serviceWorker from './serviceWorker';
import configureStore, { history } from './store';
const store = configureStore();
const app = (
<Provider store={store}>
<App history={history} />
</Provider>
);
App.js - only added necessary code lines bellow
...
import { History } from 'history'
import { ConnectedRouter } from 'connected-react-router'
...
const {history} = props;
...
return(){
...
<ConnectedRouter history={history}>
{routes}
</ConnectedRouter>
...
}
After setting up above things on your app, it will work as you want.
The other thing is we are no longer using BrowserHistory in the app because custom history has implemented.
Related
WARNING in ./node_modules/#redux-saga/core/dist/redux-saga-core.esm.js 1343:21-28
"export 'compose' was not found in 'redux'
# ./node_modules/redux-saga/dist/redux-saga-core-npm-proxy.esm.js
# ./src/store.js
# ./src/App.js
# ./src/index.js
WARNING in ./src/store.js 6:21-32
"export 'createStore' was not found in 'redux'
# ./src/App.js
# ./src/index.js
I'm facing the problem of creating a redux store. Here, I've added the sample code. If I remove the provider from App.js, it's working fine. Can anyone please help me to resolve this issue?
App.js
import React from 'react';
import Layout from './components/Layout';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { store } from './store'
const App = () => {
return (
<Provider store={store}>
<BrowserRouter>
<Layout/>
</BrowserRouter>
</Provider>
);
}
export default App;
store.js
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import reducers from './redux';
import sagas from './sagas';
const sagaMiddleware = createSagaMiddleware()
export const store = createStore(
reducers,
applyMiddleware(sagaMiddleware)
)
sagaMiddleware.run(sagas)
reducer
import { combineReducers } from 'redux';
import { reducer as auth } from './AuthRedux'
const reducers = combineReducers({
auth
});
export default reducers;
sagas
import { takeLatest, all } from 'redux-saga/effects';
import api from '../middleware/api';
import { AuthTypes } from '../redux/AuthRedux'
import { signupSaga } from './AuthSaga'
export default function * root () {
const sagaIndex = [
yield takeLatest(AuthTypes.SIGNUP, signupSaga, api),
];
yield all(sagaIndex)
}
I guess it has something to do with the redux and how I import stuff, but I'm not sure what's wrong there.😩😩
Thanks
In the store.js replace
export const store = createStore(
reducers,
applyMiddleware(sagaMiddleware)
)
with
export const store = createStore(
reducers,
{},
applyMiddleware(sagaMiddleware)
)
Just an arrow in the dark coz it worked for me maybe it should work for you
React router works normal. But if I add <Redirect> or call from <Link>, I have this exception:
Uncaught Could not find router reducer in state tree, it must be mounted under "router"
rootReducer.js:
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';
import counterReducer from './Counter/counter.reducer';
import sidebarReducer from './Sidebar/sidebar.reducer';
export default (history) => combineReducers({
router: connectRouter(history),
counter: counterReducer,
sidebar: sidebarReducer,
});
store.js:
import { createBrowserHistory } from 'history';
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from './rootReducer';
export const history = createBrowserHistory();
export default function configureStore(preloadedState) {
const composeEnhancer = compose
const store = createStore(
createRootReducer(history),
preloadedState,
composeEnhancer(
applyMiddleware(
routerMiddleware(history),
),
),
);
if (module.hot) {
module.hot.accept('./rootReducer', () => {
store.replaceReducer(createRootReducer(history));
});
}
console.log(store.getState());
return store;
}
Check the history documentation. If you're using react-router-dom#5.x.x then you should use history#4.10.1 because the latest version of history (v5) only works with react-router-dom#6.x.x
I made a single page application using React.js with a login page and perfil page. All works well but recently I noticed when refresh my page, all states are empty. Please someone can say me how to fix that issue, I mean what library import and where add it
my index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App.jsx';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();
this is my App.jsx
import React from 'react';
import '../App.css';
import AppRoutes from './AppRoutes';
import { Provider } from "react-redux";
import store from '../redux/store'
store.dispatch(getTallerList())
const App = () => (
<Provider store={store}>
<AppRoutes />
</Provider> )
export default App;
and my store.js
import { applyMiddleware, combineReducers, createStore } from 'redux'
import { ADD_TO_CART, GET_COURSE_LIST, USUARIO_LOGIN } from './action'
import { composeWithDevTools } from 'redux-devtools-extension'
import { persistStore, persistReducer } from 'redux-persist'
import thunk from 'redux-thunk'
const initialCart = {
cart:[]
}
const initialCourses ={
courses:[]
}
const initialUser ={
user:{}
}
const cartReducer = ( state = initialCart,action) => {
if(action.type===ADD_TO_CART)
{
if(state.cart.find(c=>c===action.id))
{
return state
}
return{
...state,
cart: state.cart.concat(action.id),
}
}
return state
}
const coursesReducer = (state=initialCourses, action) =>{
console.log(action)
if(action.type === GET_COURSE_LIST){
return {
...state,
courses: action.courses
}
}
return state
}
const userReducer = (state=initialUser, action)=>{
console.log(action)
if(action.type === USER_LOGIN){
return {
...state,
user: action.user
}
}
return state
}
export default createStore(combineReducers({cartReducer, coursesReducer, userReducer}), composeWithDevTools(applyMiddleware(thunk)))
Try to store value in local storage and at the time of page load get value from local storage. If you have some more values you should use redux for data storage.
It's not an issue, it's the way it works. When you refresh the entire app builds once again from the scratch.
But to persist the store upon refresh you can use these redux middlewares -
redux-persist or
redux-storage
Use this configuration as you are using redux-persist. This is my configuration, just change the main app, reducers, and actions according to your need.
import React from 'react';
import ReactDOM from 'react-dom';
import MyApp from './MyApp';
import {Provider} from 'react-redux';
import {applyMiddleware, createStore} from "redux";
import allReducers from './reducers/index';
import {persistReducer, persistStore} from 'redux-persist';
import {PersistGate} from 'redux-persist/integration/react';
import storage from 'redux-persist/lib/storage';
import thunk from "redux-thunk";
const persistConfig = {
key: 'root',
storage,
};
const persistedReducer = persistReducer(persistConfig, allReducers);
let store = createStore(persistedReducer, applyMiddleware(thunk));
let persistor = persistStore(store);
ReactDOM.render(<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<MyApp/>
</PersistGate>
</Provider>, document.getElementById('root'));
Updated : you can do like this
import {combineReducers} from "redux";
import Users from './load-user';
const allReducers = combineReducers({
users: Users,
})
export default allReducers
I'm trying to implement multiply saga, but for some reason it's stopped working to me, and i don't know why.
Here is my full code:
// store/sagas/sagas/auth.js
import { delay } from 'redux-saga';
import { put, call } from 'redux-saga/effects';
// When the client enter input on email / password textboxes on auth form.
export function* sagaFunction1(action) {
yield call(actions.SomeAction1, { 'testSeting' );
}
// store/sagas/watchers/auth.js
import { takeEvery, all } from 'redux-saga/effects';
import * as actionTypes from '../../actions/actionTypes';
import * as sagas from '../sagas/auth';
export function* watchAuthSaga() {
yield all([
takeEvery(actionTypes.SAGA_FUNCTION1, sagas.sagaFunction1)
}
// store/sagas/rootSaga.js
import { all, fork } from 'redux-saga/effects';
import * as watchers from './rootWatchers';
const sagasList = [
...watchers
];
export default function* rootSaga() {
yield all(sagasList.map(saga => fork(saga)));
}
// store/sagas/rootWatchers.js
import { watchAuthSaga } from './watchers/auth';
export default [watchAuthSaga];
// index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import './index.less';
import { BrowserRouter } from 'react-router-dom';
import { createStore, applyMiddleware, combineReducers, compose } from 'redux';
import { Provider } from 'react-redux';
import createSagaMiddleware from 'redux-saga';
import * as reducers from './store/reducers/reducers';
import rootSaga from './store/sagas/rootSaga';
import { getEnhancers } from './utils/coreUtils';
import App from './containers/App/App';
import registerServiceWorker from './registerServiceWorker';
// For redux development tools
const composeEnhancers = getEnhancers(compose);
const rootReducer = combineReducers({
auth: reducers.authReducer
});
const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer, composeEnhancers(applyMiddleware(sagaMiddleware)));
sagaMiddleware.run(rootSaga);
const app = (
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
);
ReactDOM.render(app, document.getElementById('root'));
registerServiceWorker();
What am i doing wrong?
// store/sagas/rootSaga.js
import * as watchers from './rootWatchers';
const sagasList = [
...watchers ];
Should be import watchers from './rootWatchers', because you are using export default
I am using react-router-redux.
I don't know how to create the demo to describe the issue simply.
I push all code on Github.
https://github.com/jiexishede/newReactSOAskDemo001
The a-href work well.
#https://github.com/jiexishede/newReactSOAskDemo001/blob/ask1/src/components/Home/Preview.js/#L37
Now, the push method does not work.
#https://github.com/jiexishede/newReactSOAskDemo001/blob/ask1/src/components/Home/Preview.js/#L30
I edit the code and update it on GitHub.
I import the hashHistory.
https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L9
hashHistory.push('detail/'+id); work well.
https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L32
disPatchpush #https://github.com/jiexishede/newReactSOAskDemo001/blob/286fc0e07f9d9c863f7c4fc8d9b2c09a2c45e231/src/components/Home/Preview.js#L31
It does not work.
In the Home.js:
#connect(state => {
return {
list:state.home.list,
};
}, dispatch => {
return {
actions: bindActionCreators(actions, dispatch),
dispatchPush: bindActionCreators(push, dispatch),
}
})
dispatchPush is passed from the Home.js to PreviewList to Preview.
Have your tried out?
handleClick(e) {
e.preventDefault();
this.props.history.push('/#/detail/' + id);
}
Tell me if it works or not and will update the answer accordingly.
Or if you want to try to navigate outside of components, try this.
Also try setting a route:
<Route path="/preview" component={Preview} />
That might get you the history prop.
you miss routerMiddleware. Works beautifully after applying routerMiddleware.
import { browserHistory } from 'react-router';
import { routerReducer, routerMiddleware } from 'react-router-redux';
...
const finalCreateStore = compose(
applyMiddleware(
ThunkMiddleware,
FetchMiddleware,
routerMiddleware(browserHistory)
),
DevTools.instrument(),
)(createStore);
const reducer = combineReducers({
...rootReducer,
routing: routerReducer,
});
export default function configureStore(initialState) {
const store = finalCreateStore(reducer, initialState);
return store;
}
Read this section of the docs - https://github.com/reactjs/react-router-redux#what-if-i-want-to-issue-navigation-events-via-redux-actions
If you want to navigate to another route, try Proptypes, like so:
import React, { Component, PropTypes } from 'react';
class Preview extends Component {
...
static contextTypes = {
router: PropTypes.object
};
handleNavigate(id,e) {
e.preventDefault();
this.context.router.push(`/#/detail/${id}`);
}
...
}
I had the same issue with react-router-redux and solved in the following way.
There is need to use Router not BrowserRouter. The history object has to be created with the createBrowserHistory method imported from history package.
Then the history has to be synchronized with the store using syncHistoryWithStore method imported from react-router-redux. This new history object will be passed to Router.
Then initialize the routerMiddleware passing to it the synchronized history object.
Please check out this code:
store.js
import createSagaMiddleware from 'redux-saga';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { routerReducer, routerMiddleware as reduxRouterMiddleware } from 'react-router-redux';
import { category, machine, machines, core } from './reducers';
import rootSaga from './sagas';
const rootReducer = combineReducers({
category,
machines,
machine,
core,
routing: routerReducer,
});
const initStore = (history = {}) => {
const sagaMiddleware = createSagaMiddleware();
const routerMiddleware = reduxRouterMiddleware(history);
const store = createStore(
rootReducer,
applyMiddleware(
sagaMiddleware,
routerMiddleware
)
);
sagaMiddleware.run(rootSaga);
return store;
}
export default initStore;
app.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Router } from 'react-router';
import { Provider } from 'react-redux';
import { createBrowserHistory } from 'history';
import { syncHistoryWithStore } from 'react-router-redux';
import './index.css';
import App from './App';
import initStore from './store';
import * as serviceWorker from './serviceWorker';
const browserHistory = createBrowserHistory();
const store = initStore(browserHistory)
const history = syncHistoryWithStore(browserHistory, store);
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<App />
</Router>
</Provider>,
document.getElementById('root')
);
serviceWorker.unregister();
Connected React Router requires React 16.4 and React Redux 6.0 or later.
$ npm install --save connected-react-router
Or
$ yarn add connected-react-router
Usage
Step 1
In your root reducer file,
Create a function that takes history as an argument and returns a root reducer.
Add router reducer into root reducer by passing history to connectRouter.
Note: The key MUST be router.
// reducers.js
import { combineReducers } from 'redux'
import { connectRouter } from 'connected-react-router'
const createRootReducer = (history) => combineReducers({
router: connectRouter(history),
... // rest of your reducers
})
export default createRootReducer
Step 2
When creating a Redux store,
Create a history object.
Provide the created history to the root reducer creator.
Use routerMiddleware(history) if you want to dispatch history actions (e.g. to change URL with push('/path/to/somewhere')).
// configureStore.js
import { createBrowserHistory } from 'history'
import { applyMiddleware, compose, createStore } from 'redux'
import { routerMiddleware } from 'connected-react-router'
import createRootReducer from './reducers'
...
export const history = createBrowserHistory()
export default function configureStore(preloadedState) {
const store = createStore(
createRootReducer(history), // root reducer with router state
preloadedState,
compose(
applyMiddleware(
routerMiddleware(history), // for dispatching history actions
// ... other middlewares ...
),
),
)
return store
}
Step 3
Wrap your react-router v4/v5 routing with ConnectedRouter and pass the history object as a prop. Remember to delete any usage of BrowserRouter or NativeRouter as leaving this in will cause problems synchronising the state.
Place ConnectedRouter as a child of react-redux's Provider.
N.B. If doing server-side rendering, you should still use the StaticRouter from react-router on the server.
// index.js
import { Provider } from 'react-redux'
import { Route, Switch } from 'react-router' // react-router v4/v5
import { ConnectedRouter } from 'connected-react-router'
import configureStore, { history } from './configureStore'
...
const store = configureStore(/* provide initial state if any */)
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}> { /* place ConnectedRouter under Provider */ }
<> { /* your usual react-router v4/v5 routing */ }
<Switch>
<Route exact path="/" render={() => (<div>Match</div>)} />
<Route render={() => (<div>Miss</div>)} />
</Switch>
</>
</ConnectedRouter>
</Provider>,
document.getElementById('react-root')
)