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')
)
Related
I am trying to configure an application and I am using: react class components, redux, react-redux, apollo-client, redux-persist and connected-react-redux and I am receiving the following error: "Uncaught TypeError: store.dispatch is not a function".
This is root reducer:
import { combineReducers } from "redux";
import { connectRouter } from "connected-react-router";
const createRootReducer = (history) => combineReducers({
rooter: connectRouter(history),
other reducers
})
export default createRootReducer
This is store.js:
import {createStore, applyMiddleware, compose} from 'redux'
import thunk from 'redux-thunk'
import createRootReducer from './Reducers'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'
import { createBrowserHistory } from 'history'
import { routerMiddleware } from 'connected-react-router'
const initialState = {}
export const history = createBrowserHistory()
const middware = [thunk]
const persistConfig = {
key: 'root',
storage,
}
const rootReducer = createRootReducer(history)
const persistedReducer = persistReducer(persistConfig, rootReducer)
const store = createStore(persistedReducer,
initialState,
compose(routerMiddleware(history),applyMiddleware(...middware))
)
const persistor = persistStore(store)
export {store, persistor}
And this is index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
} from "#apollo/client";
import { HashRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import {store, persistor, history} from './store';
import { PersistGate } from 'redux-persist/integration/react'
import { ConnectedRouter } from 'connected-react-router';
export const client = new ApolloClient({
uri: ' http://localhost:4000/',
cache: new InMemoryCache()
});
ReactDOM.render(
<React.StrictMode>
<ApolloProvider client={client}>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</PersistGate></Provider >
</ApolloProvider>
</React.StrictMode>,
document.getElementById('root')
);
React-router-dom version: 5.3.0. React-router version : 5.2.1
Could you please help me?
The problem was with selector, because it is using some cache memory to memoize, and at first load, there was no cache memory. I found this post.
So I deleted the selector, and moved the function inside the reducer, for which was the selector.
Also I am not using "connected-react-router" anymore
I am learning redux and came up with an example using a webservice that
returns data. Everything is working. However I configured the redux developer tools
below.
I got an error saying my store is assigned a value but never used and when I go into
my dev tools, I am not able to see my state data. Am i doing something wrong?
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import promise from 'redux-promise';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import reducers from './reducers';
import ProductsIndex from './components/products_index';
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducers,
composeEnhancers(applyMiddleware())
);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router>
<div>
<Route path="/" component={ProductsIndex} />
</div>
</Router>
</Provider>
, document.querySelector('#root'));
Error: Line 14:7: 'store' is assigned a value but never used no-unused-vars
Here is what I usually do.
configureStore.js
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import logger from "redux-logger";
import createRootReducer from "../reducers";
const middleware = window.ENV.environment === "local" ? [thunk, logger] : [thunk];
const composEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const enhancer = composEnhancers(applyMiddleware(...middleware));
const configureStore = (initialState) => {
return createStore(createRootReducer(), initialState, enhancer);
};
export default configureStore;
App.js
import configureStore from "./configureStore";
const store = configureStore();
const App = () => {
return (
<Provider store={store}>
<BrowserRouter basename={process.env.PUBLIC_URL}>
// ...
</BrowserRouter>
</Provider>
);
};
I have a front-end app built on top of react/redux/react-router. Now, I try to set up hash router. However, it only works on URL, but it does not re-render the UI.
Only way to see the view change is to refresh the browser. Then, now I see the view for the url.
When I used browser router, it automatically re-rendered the views. It will be great help if you can tell me what I missed for this current situation.
EDIT: Added my code
// index.tsx
import * as React from 'react';
import { Provider } from 'react-redux';
import { Router, Route, Switch } from 'react-router-dom';
import { Home } from './containers/home';
import { SMS } from './containers/sms';
import { history, store } from './store';
export const App = () => (
<Provider store={store}>
<Router basename="/" history={history}>
<Switch>
<Route exact path="/call" component={Home} />
<Route exact path="/sms" component={SMS} />
</Switch>
</Router>
</Provider>
);
// store.ts
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { syncHistoryWithStore, routerReducer } from 'react-router-redux';
import { createBrowserHistory, createHashHistory } from 'history';
import thunk from 'redux-thunk';
import { storage } from '../services/local-storage';
import { callsReducer } from './calls/reducer';
import { Call } from '../interfaces/call.interface';
import { CallMap } from '../interfaces/call-map.interface';
const STORAGE_NAME = 'SIP_CALL_SIMULATOR';
const {
loadState,
saveState,
} = storage({
name: STORAGE_NAME,
localStorage,
});
interface RootState {
calls: CallMap;
}
const initialState: RootState = {
calls: {},
};
const persistedState = loadState(initialState);
const reducer = combineReducers({
calls: callsReducer,
routing: routerReducer,
});
const store = createStore(reducer, persistedState, applyMiddleware(thunk));
// const browserHistory = createBrowserHistory();
const hashHistory = createHashHistory();
// const history = syncHistoryWithStore(browserHistory, store);
const history = syncHistoryWithStore(hashHistory, store);
store.subscribe(() => {
console.log(`Updated the redux store.`);
const state = store.getState();
console.log(state);
saveState(state);
});
export { history, store };
Thanks!
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.
I've been trying to use redux-perist to save my redux-state to AsyncStorage. Although I keep getting an error:
_this.store.getState is not a function
I'm not sure why this is happening?
Here is my setup:
configureStore.js:
import {AsyncStorage,} from 'react-native';
import { createStore, applyMiddleware, compose, combineReducers, } from 'redux';
import reduxThunkMiddleware from 'redux-thunk';
import Reactotron from 'reactotron';
import * as reducers from './modules';
import devTools from 'remote-redux-devtools';
import {persistStore, autoRehydrate} from 'redux-persist'
Reactotron.connect({
enabled: __DEV__,
});
const enhancer = compose(
autoRehydrate(),
applyMiddleware(
reduxThunkMiddleware,
Reactotron.reduxMiddleware,
),
devTools()
);
export default function configureStore(initialState) {
const store = createStore(
combineReducers({
...reducers,
}),
initialState,
enhancer,
);
Reactotron.addReduxStore(store, {storage: AsyncStorage});
return store;
}
App.js:
Here is where I connect my store, to my <provider>:
import React from 'react';
import {AsyncStorage} from 'react-native';
import { Provider, connect } from 'react-redux';
import { Router } from 'react-native-router-flux';
import routes from '#routes/app';
import createStore from './redux/create'; // Returns store object from the above configureStore.js!
import {persistStore} from 'redux-persist'
const RouterWithRedux = connect()(Router);
const store = persistStore(createStore(), {storage: AsyncStorage}); // Not working??
const Kernel = () => (
<Provider store={store}>
<RouterWithRedux scenes={routes} />
</Provider>
);
export default Kernel;
const RouterWithRedux = connect()(Router);
const store = createStore();
const persistor = persistStore(store, {storage: AsyncStorage}); // Not working??
const Kernel = () => (
<Provider store={store} persistor={persistor}>
<RouterWithRedux scenes={routes} />
</Provider>
);
The problem was I had to pass down a persistor field as well as the store field.
After adding in the persistor field, my store was being persisted into AsyncStorage
EDIT:
This worked at the time - It has occured to me that this not the correct solution to the problem. But I'm still getting responses that it still works, if someone could provide another answer for everyone else, that'd be great.