I'm trying to implement this example to get my boilerplate router/redux/immutable working:
https://github.com/sjparsons/react-router-redux-immutable
However I'm coming across an error I don't see documented elsewhere and I'm not sure where to go with it. This is the error
combineReducers.js:29 Unexpected property "0" found in previous state received by the reducer. Expected to find one of the known reducer property names instead: "todos", "routing". Unexpected properties will be ignored.
I'm also receiving this error, not sure one is a result of the other:
redux-router-init.js:69 Uncaught TypeError: Cannot read property 'toJS' of undefined
There are my reducers:
todos.js
import Immutable from 'immutable'
export default (state = Immutable.List(['Code More!']), action) => {
switch(action.type) {
case 'addTodo':
return state.push(action.todo)
default:
return state
}
}
router-reducer.js
/**
* A custom router reducer to support an Immutable store.
* See: https://github.com/gajus/redux-immutable#using-with-react-router-redux
*/
import Immutable from 'immutable';
import {
LOCATION_CHANGE
} from 'react-router-redux';
const initialState = Immutable.fromJS({
locationBeforeTransitions: null
});
export default (state = initialState, action) => {
if (action.type === LOCATION_CHANGE) {
return state.merge({
locationBeforeTransitions: action.payload
});
}
return state;
};
Here's where I initialize the new store and history:
redux-router-init.js
/* External dependencies */
import { combineReducers } from 'redux-immutable';
import Immutable from 'immutable';
import { createStore, compose, applyMiddleware } from 'redux';
import { hashHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import createLogger from 'redux-logger';
import DevTools from './components/DevTools';
/* Internal dependencies */
import todoReducer from './reducers/todos';
import routerReducer from './reducers/router-reducer';
////////////////////////////////////////////////
/**
* Combine reducers into root reducer and create store.
* Note thate 'combineReducers' is a redux-immutable version
*/
const rootReducer = combineReducers({
todos: todoReducer,
routing: routerReducer
})
const initialState = Immutable.List(['Code More!']);
const logger = createLogger();
const store = createStore(
rootReducer,
initialState,
compose(
applyMiddleware(logger),
DevTools.instrument()
)
);
/* Create enhanced history object for router */
const createSelectLocationState = () => {
let prevRoutingState, prevRoutingStateJS;
return (state) => {
console.log(state);
const routingState = state.get('routing'); // or state.routing
if (typeof prevRoutingState === 'undefined' || prevRoutingState !== routingState) {
prevRoutingState = routingState;
prevRoutingStateJS = routingState.toJS();
}
return prevRoutingStateJS;
};
};
const history = syncHistoryWithStore(hashHistory, store, {
selectLocationState: createSelectLocationState()
});
////////////////////////////////////////////////
/* Exports */
export { store, history }
And here is the index where I tie it into the router:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import {Router, Route, IndexRoute, hashHistory} from 'react-router';
import App from './components/App';
import About from './components/About';
import Todos from './components/Todos';
import DevTools from './components/DevTools';
import {store, history} from './redux-router-init';
ReactDOM.render(
<Provider store={store}>
<div>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Todos}/>
<Route path="/about" component={About}/>
<Route path="/todos" component={Todos}/>
</Route>
</Router>
{ DEVELOPMENT ? <DevTools/> : ''}
</div>
</Provider>,
document.getElementById('root')
);
The full app in its current state can be located here:
https://github.com/tim37123/my-boilerplate/tree/react-redux-devtools-immutable-router
I think the error happens because of this line:
const initialState = Immutable.List(['Code More!']);
It's because immutable is expected to have a mapping of property keys while it's given List which is an indexed mapping thus the error says '0'.
Changing the line to
const initialState = Immutable.Map();
should fix the issue.
You can also do this:
const initialState = Immutable.Map({
todos: Immutable.List(),
});
Related
I have the following Redux store:
import {createStore} from 'redux';
import rootReducer from './reducers';
export function configureStore() {
const store = createStore(rootReducer);
return store;
};
const store = configureStore()
export default store;
This is the rootReducer created with combineReducers:
import {combineReducers} from 'redux';
import application from '../features/application/reducers';
const rootReducer = combineReducers({
application,
});
export default rootReducer;
And this is the creation of the provider:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import store from './app/store';
import { Provider } from 'react-redux';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
The problem is that I am getting the following error:
Error: The slice reducer for key "application" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.
I checked this documentation, and I can't find a solution to my problem.
EDIT
I see that the problem might be related to webpack, but I have no idea of this:
This is the code for application reducer:
import { ActionInterface } from '../generals';
import {
FETCH_APPLICATION_COMPOSITE_SUCCESS,
SET_CURRENT_APPLICATION_COMPONENT
} from './actions';
const INIT_STATE = {
applicationComposite: null,
currentApplicationComponent: null
}
export default (state=INIT_STATE, action: ActionInterface) => {
switch(action.type) {
case FETCH_APPLICATION_COMPOSITE_SUCCESS: {
return {
...state,
//#ts-ignore: Object is possibly 'undefined'
applicationComposite: action.payload.applicationComposite
}
}
case SET_CURRENT_APPLICATION_COMPONENT: {
return {
...state,
//#ts-ignore: Object is possibly 'undefined'
currentApplicationComponent: action.payload.applicationComponent
}
}
}
}
You need to add default return to your reducer
import { ActionInterface } from '../generals';
import {
FETCH_APPLICATION_COMPOSITE_SUCCESS,
SET_CURRENT_APPLICATION_COMPONENT
} from './actions';
const INIT_STATE = {
applicationComposite: null,
currentApplicationComponent: null
}
export default (state=INIT_STATE, action: ActionInterface) => {
switch(action.type) {
case FETCH_APPLICATION_COMPOSITE_SUCCESS: {
return {
...state,
//#ts-ignore: Object is possibly 'undefined'
applicationComposite: action.payload.applicationComposite
}
}
case SET_CURRENT_APPLICATION_COMPONENT: {
return {
...state,
//#ts-ignore: Object is possibly 'undefined'
currentApplicationComponent: action.payload.applicationComponent
}
}
default: return state;
}
}
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!
So I've recently started learning Redux and now I'm trying to make my first app with it, but I've stumbled upon a problem which I cannot resolve on my own. Basically I want a user to click a button (there will be authentication) and fetch all his or hers data from Firebase and display it.
Here is my index.js:
// Dependencies
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, combineReducers } from 'redux';
import createHistory from 'history/createBrowserHistory';
import { ConnectedRouter, routerReducer, routerMiddleware } from 'react-router-redux';
import ReduxPromise from "redux-promise";
import ReduxThunk from 'redux-thunk';
// Reducers
import rootReducer from './reducers';
// ServiceWorker
import registerServiceWorker from './registerServiceWorker.js';
// Styles
import './styles/index.css';
// Components
import App from './containers/App.js';
const history = createHistory();
const middleware = routerMiddleware(history);
// Create store
const store = createStore(
combineReducers({
...rootReducer,
router: routerReducer
}),
applyMiddleware(ReduxThunk, middleware, ReduxPromise)
)
ReactDOM.render((
<Provider store={store}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</Provider>
), document.getElementById('root'));
registerServiceWorker();
And my main container, App.js:
import React, { Component } from 'react';
import { Route, Switch, withRouter } from 'react-router-dom'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import firebase from 'firebase';
import firebaseConfig from '../firebaseConfig.js';
// Actions
import { fetchAllMonths } from "../actions/index";
// Static components
import Nav from '../components/Nav.js';
// Routes
import CurrentMonth from '../components/CurrentMonth.js';
import AddNewMonth from '../components/AddNewMonth.js';
import Archive from '../components/Archive.js';
import Settings from '../components/Settings.js';
class App extends Component {
constructor (props) {
super(props);
this.login = this.login.bind(this);
}
componentWillMount() {
firebase.initializeApp(firebaseConfig);
firebase.auth().signInAnonymously().catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
});
}
login() {
this.props.fetchAllMonths();
}
render() {
if (this.props.data === undefined) {
return (
<button onClick={this.login}>Login</button>
)
} else if (this.props.data !== undefined) {
return (
<main className="main-container">
<Nav user="user"/>
<Switch>
<Route exact path='/' component={CurrentMonth}/>
<Route path='/aktualny' component={CurrentMonth}/>
<Route path='/nowy' component={AddNewMonth}/>
<Route path='/archiwum' component={Archive}/>
<Route path='/ustawienia' component={Settings}/>
</Switch>
</main>
);
}
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ fetchAllMonths }, dispatch);
}
function mapStateToProps({ data }) {
return { data };
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App))
Main action, fetchAllMonths:
// import firebase from 'firebase';
// Firebase Config
// import axios from 'axios';
export const FETCH_ALL_MONTHS = 'FETCH_ALL_MONTHS';
export function fetchAllMonths() {
/*const database = firebase.database();
const data = database.ref('/users/grhu').on('value', function(snapshot) {
return snapshot.val();
});
console.log(data) */
const data = fetch('https://my-finances-app-ef6dc.firebaseio.com/users/grhu.json')
.then(async (response) => response.json())
.then(data => {
console.log(data);
return data;
}
)
console.log(data);
return {
type: FETCH_ALL_MONTHS,
payload: data
};
};
Reducers index.js:
import { combineReducers } from "redux";
import data from "./reducer_load_from_db";
const rootReducer = combineReducers({
data: data
});
export default rootReducer;
And finally my reducer:
import { FETCH_ALL_MONTHS } from "../actions/index";
export default function(state = [], action) {
switch (action.type) {
case FETCH_ALL_MONTHS:
return [action.payload.data, ...state];
default:
return state;
}
return state;
}
So I'm sure that fetch works fine, because console.log(data) gives me a valid JSON file, but second console.log(data) with the passed const gives me a promise, which then I send as a payload to a Reducer. CreateStore also seems to work, because in the React dev console I can see a "data" prop in App container. I use redux-promise which should resolve the Promise in payload and return a JSON to the store, but data remains undefined. Also tried redux-promise-middleware, but again, no luck.
What am I missing? I've looked at that code for several hours and I cannot understand what is wrong with it.
I'll appreciate all the answers, but i really want to understand the issue, not just copy-paste a solution.
Thanks in advance!
Initial Answer
From what I'm reading in your fetchAllMonths() action creator, you're setting a property on the action it returns called payload equal to the data returned from your API call.
return {
type: FETCH_ALL_MONTHS,
payload: data
};
If you logged action.payload in your reducer like so...
switch (action.type) {
case FETCH_ALL_MONTHS:
console.log(action.payload)
return [action.payload.data, ...state];
default:
return state;
}
I believe you'd see the data returned from your API call.
So then in your reducer you would be expecting action.payload as a property of the FETCH_ALL_MONTHS action. And you'd want to use the spread operator ...action.payload.
Also, to make your logic a little easier to read, why not try using an async action to fetch data and then dispatch an action that takes in the data returned from the API call?
Hope that helps!
Updated Answer
As I thought about this and read your reply to my answer, I think you may need to use an async action to ensure your data was successfully fetched. I made a really simple CodePen example using async actions.
https://codepen.io/joehdodd/pen/rJRbZG?editors=0010
Let me know if that helps and if you get it working that way.
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')
)
I have the following state - action history:
My problem is that I expect a state with zoneCategories : Array[8757] , so I'm doing something wrong in my reducer, which is:
let setZoneCategoriesReducer = function (zoneCategories = [], action) {
switch (action.type) {
case 'SET_CATEGORIES_FROM_SERVER':
return [
...zoneCategories, action.zoneCategories
]
default:
return zoneCategories;
}
}
export default setZoneCategoriesReducer
Here is my Store:
import {applyMiddleware, compose, createStore} from 'redux'
import rootReducer from './reducers'
import logger from 'redux-logger'
import thunk from 'redux-thunk'
let finalCreateStore = compose(
applyMiddleware(thunk, logger())
)(createStore)
export default function configureStore(initialState = {zoneCategories: []}) {
return finalCreateStore(rootReducer, initialState)
}
And here my App entrypoint:
import React from 'react';
import App from './App';
import './index.css';
import { Provider } from 'react-redux';
import configureStore from './redux/store'
import { render } from 'react-dom'
let initialState = {
zoneCategories: []
}
let store = configureStore(initialState)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
Also, my root reducer:
import { combineReducers } from 'redux'
import setZoneCategoriesReducer from './setZoneCategoriesReducer'
const rootReducer = combineReducers({
zoneCategories: setZoneCategoriesReducer
})
export default rootReducer
I'm mentally blocked right now, any help?
In your setZoneCategoriesReducer function, you add action.zoneCategories as an element of the returned state, which presumably contains the 8757 elements you actually need. Spread it instead of adding directly.
let setZoneCategoriesReducer = function (zoneCategories = [], action) {
// ...
return [
...zoneCategories, ...action.zoneCategories
]
// ...
}
}