I m learning deeper redux and I m having some trouble dealing with higher order reducers.
I m trying to understand how it works using a simple example of pagination.
NB : The below code is just a quick example of redux in nodejs context, without transpilation and good practices, and thus, I don't have access to spread / destruc operator, so I m using it statefully, while it's not a good practice at all, and I know that
So, let's imagine that I have a paginable higher order reducer :
const paginable = (reducer, options) => {
const PAGE_OFFSET = options.limit;
const ATTRIBUTE_TO_SLICE = options.attr;
const initialState = {
all: reducer(undefined, {}),
displayed: [],
limit: PAGE_OFFSET,
currentPage: 1
};
const _actionHandler = {
'CHANGE_PAGE': (state, newPage) => ({all: state.all, displayed: state.displayed, currentPage: newPage, limit: PAGE_OFFSET}),
'CHANGE_DISPLAYED': state => ({
all: state.all, currentPage: state.currentPage, limit: PAGE_OFFSET,
displayed: state.all[ATTRIBUTE_TO_SLICE].slice((state.currentPage - 1) * PAGE_OFFSET,
state.currentPage * PAGE_OFFSET)
})
};
return (state = initialState, action) => {
const handler = _actionHandler[action.type];
if (handler) {
return handler(state, action.payload);
}
const newAll = reducer(state.all, action);
state.all = newAll;
return state;
};
};
module.exports = paginable;
That I want to apply on these two reducers :
const _actionHandler = {
'ADD': (state, item) => ({list: [...state.list, item]})
};
const initialState = {
list: ['a', 'b', 'c', 'd', 'e']
};
const listReducer = (state = initialState, action) => {
const handler = _actionHandler[action.type];
return handler ? handler(state, action.payload) : state;
};
module.exports = listReducer;
and
const initialState = {
arr: ['z', 'x', 'y', 'b', 'b', 'c', 'd']
};
const arrayReducer = (state = initialState) => {
return state;
};
module.exports = arrayReducer;
I create my store as following :
const redux = require('redux');
const listReducer = require('./reducer/list');
const arrayReducer = require('./reducer/arrayOfX');
const paginable = require('./reducer/paginable');
const reducers = redux.combineReducers({
list: paginable(listReducer, {limit: 2, attr: 'list'}),
arr: paginable(arrayReducer, {limit: 3, attr: 'arr'})
});
const store = redux.createStore(reducers);
My problem now, is that each time I will dispatch an action like CHANGE_PAGE or CHANGE_DISPLAYED, it always will be handled by the two reducers arr and list, that I don't want.
I had in mind to create new actions like CHANGE_DISPLAYED_LIST and CHANGE_DISPLAYED_ARRAY but it would force me to manage more actions in the paginable reducer that I absolutely dont want to... I m probably missing something important out there.
Any suggestions ?
You dont need 2 reducers for this actually. A single Higher order reducer can do the job.
We can pass the type to the parent wrapper and return a function from it. This creates 2 entries in your state.
So, lets create the higher order reducer first:-
const initialState = {
all: {},
displayed: [],
limit: PAGE_OFFSET,
currentPage: 1
};
export default function wrapper(type) {
return function(state=initialState,action) {
//using es6 literals to concatenate the string
case `CHANGE_DISPLAYED_${type}`:
// update your state
case `CHANGE_PAGE_${type}`:
// update your state
}
}
Now, call the reducers in following way
const indexReducer = combineReducers({
"arrayType": wrapper("array"),
"listType" : wrapper("list")
})
For more info you can check out for reusing reducer logic here.
Let me know if you face any issues.
Related
I have an array of product objects inside my reducer and I have an empty array of brand as well. I want to add all the unique brands from my products object array into my brands array in my reducer, is there any way I can do that?
My Reducer:
import * as actionTypes from './shop-types';
const INITIAL_STATE = {
products: [
{
id: 1,
brand:"DNMX"
},
{
id: 2,
brand: "Aeropostale",
},
{
id: 3,
brand: "AJIO",
},
{
id: 4,
brand: "Nike",
},
],
cart: [],
brands: [], //<---- I want to add all the unique brands inside this array
currentProduct: null,
};
const shopReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case actionTypes.ADD_TO_CART:
const product = state.products.find(
(product) => product.id === action.payload.id
);
if (product !== null) {
return {
...state,
cart: state.cart.concat(product),
};
} else {
return null;
}
default:
return state;
}
};
export default shopReducer;
Brands is essentially derived data, meaning it's based off, or reliant on other data. Because of this, you don't actually need to set it in state, and instead rather, just derive it.
I'd normally recommend using Redux Toolkit as it's far simpler, but as you're using old-school Redux, I'd recommend using a library called Reselect. It's a library for creating memoized selectors that you can consume in your component.
For your example, I'd try something like:
// import the createSelector function
// we'll use to make a selector
import { createSelector } from "reselect"
// create a "getter". this is just a simplified
// way of accessing state
const selectBrands = (state) => state.products
// create the selector. this particular selector
// just looks at `products` in state (from your
// getter), and filters out duplicate values
// and returns a unique list
const uniqueBrands = createSelector(selectBrands, (items) =>
items.filter(
(item, idx, arr) =>
arr.findIndex((brand) => brand.name === item.name) === idx
)
)
Then in your component code, you can access this in mapStateToProps:
const mapStateToProps = (state) => ({
uniqueBrands: uniqueBrands(state),
})
This is currently untested, but should be what you're looking for.
It's not really clear if you mean unique brands by cart or products, but it shouldn't change the patterns you'll use to solve this.
First assuming the product list isn't changing, you can simply add them as part of the initial state.
const ALL_PRODUCTS = [
{ id: 1, brand:"DNMX" },
{ id: 2, brand: "Aeropostale" },
{ id: 3, brand: "AJIO" },
{ id: 4, brand: "Nike" }
];
const distinct = (array) => Array.from(new Set((array) => array.map((x) => x.brand)).entries());
const ALL_BRANDS = distinct(ALL_PRODUCTS.map((x) => x.brand));
const INITIAL_STATE = {
products: ALL_PRODUCTS,
cart: [],
brands: ALL_BRANDS,
currentProduct: null,
};
If you will have an action that will add a new products and the brands have to reflect that you just apply the above logic during the state updates for the products.
const reducer = (state = INITIAL_STATE, action) => {
switch(action.type) {
case (action.type === "ADD_PRODUCT") {
const products = [...state.products, action.product];
return {
...state,
products,
brands: distinct(products.map((x) => x.brand))
}
}
}
return state;
};
Now for the idiomatic way. You might note that brands can be considered derived from the products collection. Meaning we probably dont even need it in state since we can use something called a selector to create derived values from our state which can greatly simplify our reducer/structure logic.
// we dont need brands in here anymore, we can derive.
const INITIAL_STATE = {
products: ALL_PRODUCTS,
cart: [],
currentProduct: null;
};
const selectAllBrands = (state) => {
return distinct(state.products.map((x) => x.brand))
};
Now when we add/remove/edit new products we no longer need to update the brand slice. It will be derived from the current state of products. On top of all of that, you can compose selectors just like you can with reducers to get some really complex logic without mucking up your store.
const selectCart = (state) => state.cart;
const selectAllBrands = (state) => {...see above}
const selectTopBrandInCart = (state) => {
const cart = selectCart(state);
const brands = selectBrands(brands);
// find most popular brand in cart and return it.
};
I would highly recommend you check out reselect to help build composable and performant selectors.
How do I add elements in my array arr[] of redux state in reducer?
I am doing this-
import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {
arr:[]
}
export default function userState(state = initialUserState, action)
{
console.log(arr);
switch (action.type)
{
case ADD_ITEM:
return {
...state,
arr: state.arr.push([action.newItem])
}
default:
return state
}
}
Two different options to add item to an array without mutation
case ADD_ITEM :
return {
...state,
arr: [...state.arr, action.newItem]
}
OR
case ADD_ITEM :
return {
...state,
arr: state.arr.concat(action.newItem)
}
push does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:
import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {
arr:[]
}
export default function userState(state = initialUserState, action){
console.log(arr);
switch (action.type){
case ADD_ITEM :
return {
...state,
arr:[...state.arr, action.newItem]
}
default:return state
}
}
If you need to insert into a specific position in the array, you can do this:
case ADD_ITEM :
return {
...state,
arr: [
...state.arr.slice(0, action.pos),
action.newItem,
...state.arr.slice(action.pos),
],
}
Since this question gets a lot of exposure:
If you are looking for the answer to this question, there is a good chance that you are following a very outdated Redux tutorial.
The official recommendation (since 2019) is to use the official Redux Toolkit to write modern Redux code.
Among other things, that will eliminate string action constants and generate action creators for you.
It will also employ methods that allow you to just write mutating logic in your Reducers created by createReducer or createSlice, so there is no need to write immutable code in Reducers in modern Redux in the first place.
Please follow the official Redux tutorials instead of third-party tutorials to always get the most up-to-date information on good Redux practices and will also show you how to use Redux Toolkit in different common scenarios.
For comparison, in modern Redux this would look like
const userSlice = createSlice({
name: "user",
initialState: {
arr:[]
},
reducers: {
// no ACTION_TYPES, this will internally create a type "user/addItem" that you will never use by hand. You will only see it in the devTools
addItem(state, action) {
// you can use mutable logic in createSlice reducers
state.arr.push(action.payload)
}
}
})
// autogenerated action creators
export const { addItem } = slice.actions;
// and export the final reducer
export default slice.reducer;
If you want to combine two arrays, one after another then you can use
//initial state
const initialState = {
array: [],
}
...
case ADD_ARRAY :
return {
...state,
array: [...state.array, ...action.newArr],
}
//if array = [1,2,3,4]
//and newArr = [5,6,7]
//then updated array will be -> [1,2,3,4,5,6,7]
...
This Spread operator (...) iterates array element and store inside the array [ ] or spreading element in the array, what you can simply do using "for loop" or with any other loop.
I have a sample
import * as types from '../../helpers/ActionTypes';
var initialState = {
changedValues: {}
};
const quickEdit = (state = initialState, action) => {
switch (action.type) {
case types.PRODUCT_QUICKEDIT:
{
const item = action.item;
const changedValues = {
...state.changedValues,
[item.id]: item,
};
return {
...state,
loading: true,
changedValues: changedValues,
};
}
default:
{
return state;
}
}
};
export default quickEdit;
The easiest solution to nested arrays is concat():
case ADD_ITEM:
state.array = state.array.concat(action.paylod)
return state
concat() spits out an updated array without mutating the state. Simply set the array to the output of concat() and return the state.
This worked for me
//Form side
const handleSubmit = (e) => {
e.preventDefault();
let Userdata = { ...userdata, id: uuidv4() };
dispatch(setData(Userdata));
};
//Reducer side
const initialState = {
data: [],
};
export const dataReducer = (state = initialState, action) => {
switch (action.type) {
case ActionTypes.SET_DATA:
return { ...state, data: [...state.data, action.payload] };
default:
return state;
}
};
I am experienced js/React developer but came across case that I can't solve and I don't have idea how to fix it.
I have one context provider with many different state, but one state looks like following:
const defaultParams = {
ordering: 'price_asc',
page: 1,
perPage: 15,
attrs: {},
}
const InnerPageContext = createContext()
export const InnerPageContextProvider = ({ children }) => {
const [params, setParams] = useState({ ...defaultParams })
const clearParams = () => {
setParams({...defaultParams})
}
console.log(defaultParams)
return (
<InnerPageContext.Provider
value={{
params: params,
setParam: setParam,
clearParams:clearParams
}}
>
{children}
</InnerPageContext.Provider>
)
}
I have one button on page, which calls clearParams function and it should reset params to default value.
But it does not works
Even when i console.log(defaultParams) on every provider rerendering, it seems that defaultParams variable is also changing when state changes
I don't think it's normal because I have used {...defaultParams} and it should create new variable and then pass it to useState hook.
I have tried:
const [params, setParams] = useState(Object.assign({}, defaultParams))
const clearParams = () => {
setParams(Object.assign({}, defaultParams))
}
const [params, setParams] = useState(defaultParams)
const clearParams = () => {
setParams(defaultParams)
}
const [params, setParams] = useState(defaultParams)
const clearParams = () => {
setParams({
ordering: 'price_asc',
page: 1,
perPage: 15,
attrs: {},
})
}
None of above method works but 3-rd where I hard-coded same object as defaultParams.
The idea is to save dafult params somewhere and when user clears params restore to it.
Do you guys have some idea hot to make that?
Edit:
This is how I update my params:
const setParam = (key, value, type = null) => {
setParams(old => {
if (type) {
old[type][key] = value
} else old[key] = value
console.log('Params', old)
return { ...old }
})
}
please show how you update the "params".
if there is something like this in the code "params.attrs.test = true" then defaultParams will be changed
if old[type] is not a simple type, it stores a reference to the same object in defaultParams. defaultParams.attrs === params.attrs. Since during initialization you destructuring an object but not its nested objects.
the problem is here: old[type][key] = value
solution:
const setParam = (key, value, type = null) => {
setParams(old => {
if (type) {
old[type] = {
...old[type],
key: value,
}
} else old[key] = value
return { ...old }
})
}
I have a scenario where I have 2 reducers that are the result of a combineReducers. I want to combine them together, but keep their keys at the same level on nesting.
For example, given the following reducers
const reducerA = combineReducers({ reducerA1, reducerA2 })
const reducerB = combineReducers{{ reducerB1, reducerB2 })
I want to end up with a structure like:
{
reducerA1: ...,
reducerA2: ...,
reducerB1: ...,
reducerB2: ...
}
If I use combineReducers again on reducerA and reducerB like so:
const reducer = combineReducers({ reducerA, reducersB })
I end up with a structure like:
{
reducerA: {
reducerA1: ...,
reducerA2: ...
},
reducerB: {
reducerB1: ...,
reducerB2: ...
}
}
I can't combine reducerA1, reducerA2, reducerB1 and reducerB2 in a single combineReducers call as reducerA and reducerB are being provided to me already combined from different npm packages.
I have tried using the reduce-reducers library to combine them togethers and reduce the state together, an idea I got from looking at the redux docs, like so:
const reducer = reduceReducers(reducerA, reducerB)
Unfortunately this did not work as the resulting reducer from combineReducers producers a warning if unknown keys are found and ignores them when returning its state, so the resulting structure only contains that of reducerB:
{
reducerB1: ...,
reducerB2: ...
}
I don't really want to implement my own combineReducers that does not enforce the structure so strictly if I don't have to, so I'm hoping someone knows of another way, either built-in to redux or from a library that can help me with this. Any ideas?
Edit:
There was an answer provided (it appears to have been deleted now) that suggested using flat-combine-reducers library:
const reducer = flatCombineReducers(reducerA, reducerB)
This was one step closer than reduce-reducers in that it managed to keep the keep the state from both reducerA and reducerB, but the warning messages are still being produced, which makes me wonder if the vanishing state I observed before was not combineReducers throwing it away, but rather something else going on with the reduce-reducers implementation.
The warning messages are:
Unexpected keys "reducerB1", "reducerB2" found in previous state received by the reducer. Expected to find one of the known reducer keys instead: "reducerA1", "reducerA2". Unexpected keys will be ignored.
Unexpected keys "reducerA1", "reducerA2" found in previous state received by the reducer. Expected to find one of the known reducer keys instead: "reducerB1", "reducerB2". Unexpected keys will be ignored.
If I do a production build, the warning disappear (such is the way for many react/redux warnings), but I'd rather them not appear at all.
I've also done some more searching for other libraries and found redux-concatenate-reducers:
const reducer = concatenateReducers([reducerA, reducerB])
This has the same result as flat-combine-reducers so the search continues.
Edit 2:
A few people have made some suggestions now but none have worked so far, so here is a test to help:
import { combineReducers, createStore } from 'redux'
describe('Sample Tests', () => {
const reducerA1 = (state = 0) => state
const reducerA2 = (state = { test: "value1"}) => state
const reducerB1 = (state = [ "value" ]) => state
const reducerB2 = (state = { test: "value2"}) => state
const reducerA = combineReducers({ reducerA1, reducerA2 })
const reducerB = combineReducers({ reducerB1, reducerB2 })
const mergeReducers = (...reducers) => (state, action) => {
return /* your attempt goes here */
}
it('should merge reducers', () => {
const reducer = mergeReducers(reducerA, reducerB)
const store = createStore(reducer)
const state = store.getState()
const expectedState = {
reducerA1: 0,
reducerA2: {
test: "value1"
},
reducerB1: [ "value" ],
reducerB2: {
test: "value2"
}
}
expect(state).to.deep.equal(expectedState)
})
})
The goal is to get this test to pass AND not produce any warnings in the console.
Edit 3:
Added more tests to cover more cases, including handling an action after the initial creation and if the store is created with initial state.
import { combineReducers, createStore } from 'redux'
describe('Sample Tests', () => {
const reducerA1 = (state = 0) => state
const reducerA2 = (state = { test: "valueA" }) => state
const reducerB1 = (state = [ "value" ]) => state
const reducerB2 = (state = {}, action) => action.type == 'ADD_STATE' ? { ...state, test: (state.test || "value") + "B" } : state
const reducerA = combineReducers({ reducerA1, reducerA2 })
const reducerB = combineReducers({ reducerB1, reducerB2 })
// from Javaguru's answer
const mergeReducers = (reducer1, reducer2) => (state, action) => ({
...state,
...reducer1(state, action),
...reducer2(state, action)
})
it('should merge combined reducers', () => {
const reducer = mergeReducers(reducerA, reducerB)
const store = createStore(reducer)
const state = store.getState()
const expectedState = {
reducerA1: 0,
reducerA2: {
test: "valueA"
},
reducerB1: [ "value" ],
reducerB2: {}
}
expect(state).to.deep.equal(expectedState)
})
it('should merge basic reducers', () => {
const reducer = mergeReducers(reducerA2, reducerB2)
const store = createStore(reducer)
const state = store.getState()
const expectedState = {
test: "valueA"
}
expect(state).to.deep.equal(expectedState)
})
it('should merge combined reducers and handle actions', () => {
const reducer = mergeReducers(reducerA, reducerB)
const store = createStore(reducer)
store.dispatch({ type: "ADD_STATE" })
const state = store.getState()
const expectedState = {
reducerA1: 0,
reducerA2: {
test: "valueA"
},
reducerB1: [ "value" ],
reducerB2: {
test: "valueB"
}
}
expect(state).to.deep.equal(expectedState)
})
it('should merge basic reducers and handle actions', () => {
const reducer = mergeReducers(reducerA2, reducerB2)
const store = createStore(reducer)
store.dispatch({ type: "ADD_STATE" })
const state = store.getState()
const expectedState = {
test: "valueAB"
}
expect(state).to.deep.equal(expectedState)
})
it('should merge combined reducers with initial state', () => {
const reducer = mergeReducers(reducerA, reducerB)
const store = createStore(reducer, { reducerA1: 1, reducerB1: [ "other" ] })
const state = store.getState()
const expectedState = {
reducerA1: 1,
reducerA2: {
test: "valueA"
},
reducerB1: [ "other" ],
reducerB2: {}
}
expect(state).to.deep.equal(expectedState)
})
it('should merge basic reducers with initial state', () => {
const reducer = mergeReducers(reducerA2, reducerB2)
const store = createStore(reducer, { test: "valueC" })
const state = store.getState()
const expectedState = {
test: "valueC"
}
expect(state).to.deep.equal(expectedState)
})
it('should merge combined reducers with initial state and handle actions', () => {
const reducer = mergeReducers(reducerA, reducerB)
const store = createStore(reducer, { reducerA1: 1, reducerB1: [ "other" ] })
store.dispatch({ type: "ADD_STATE" })
const state = store.getState()
const expectedState = {
reducerA1: 1,
reducerA2: {
test: "valueA"
},
reducerB1: [ "other" ],
reducerB2: {
test: "valueB"
}
}
expect(state).to.deep.equal(expectedState)
})
it('should merge basic reducers with initial state and handle actions', () => {
const reducer = mergeReducers(reducerA2, reducerB2)
const store = createStore(reducer, { test: "valueC" })
store.dispatch({ type: "ADD_STATE" })
const state = store.getState()
const expectedState = {
test: "valueCB"
}
expect(state).to.deep.equal(expectedState)
})
})
The above mergeReducers implementation passes all the tests, but still producers warnings to the console.
Sample Tests
✓ should merge combined reducers
✓ should merge basic reducers
Unexpected keys "reducerB1", "reducerB2" found in previous state received by the reducer. Expected to find one of the known reducer keys instead: "reducerA1", "reducerA2". Unexpected keys will be ignored.
Unexpected keys "reducerA1", "reducerA2" found in previous state received by the reducer. Expected to find one of the known reducer keys instead: "reducerB1", "reducerB2". Unexpected keys will be ignored.
✓ should merge combined reducers and handle actions
✓ should merge basic reducers and handle actions
✓ should merge combined reducers with initial state
✓ should merge basic reducers with initial state
✓ should merge combined reducers with initial state and handle actions
✓ should merge basic reducers with initial state and handle actions
It is important to note that the warnings being printed are for the test case immediately after and that combineReducers reducers will only print each unique warning once, so because I'm reusing the reducer between tests, the warnings are only shown for the first test case to produce it (I could combine the reducers in each test to prevent this, but as the criteria I'm looking for it to not produce them at all, I'm happy with this for now).
If you are attempting this, I don't mind if mergeReducers accepts 2 reducers (like above), an array of reducers or an object of reducers (like combineReducers). Actually, I don't mind how it is achieved as long as it doesn't require any changes to the creation of reducerA, reducerB, reducerA1, reducerA1, reducerB1 or reducerB2.
Edit 4:
My current solution is modified from Jason Geomaat's answer.
The idea is to filter the state being provided to the reducer using the keys of previous calls by using the following wrapper:
export const filteredReducer = (reducer) => {
let knownKeys = Object.keys(reducer(undefined, { type: '##FILTER/INIT' }))
return (state, action) => {
let filteredState = state
if (knownKeys.length && state !== undefined) {
filteredState = knownKeys.reduce((current, key) => {
current[key] = state[key];
return current
}, {})
}
let newState = reducer(filteredState, action)
let nextState = state
if (newState !== filteredState) {
knownKeys = Object.keys(newState)
nextState = {
...state,
...newState
}
}
return nextState;
};
}
I merge the result of the filtered reducers using the redux-concatenate-reducers library (could have used flat-combine-reducers but the merge implementation of the former seems a bit more robust). The mergeReducers function looks like:
const mergeReducers = (...reducers) => concatenateReducers(reducers.map((reducer) => filterReducer(reducer))
This is called like so:
const store = createStore(mergeReducers(reducerA, reducerB)
This passes all of the tests and doesn't produce any warnings from reducers created with combineReducers.
The only bit I'm not sure about is where the knownKeys array is being seeded by calling the reducer with an INIT action. It works, but it feels a little dirty. If I don't do this, the only warning that is produced is if the store is created with an initial state (the extra keys are not filtered out when resolving the initial state of the reducer.
Ok, decided to do it for fun, not too much code... This will wrap a reducer and only provide it with keys that it has returned itself.
// don't provide keys to reducers that don't supply them
const filterReducer = (reducer) => {
let lastState = undefined;
return (state, action) => {
if (lastState === undefined || state == undefined) {
lastState = reducer(state, action);
return lastState;
}
var filteredState = {};
Object.keys(lastState).forEach( (key) => {
filteredState[key] = state[key];
});
var newState = reducer(filteredState, action);
lastState = newState;
return newState;
};
}
In your tests:
const reducerA = filterReducer(combineReducers({ reducerA1, reducerA2 }))
const reducerB = filterReducer(combineReducers({ reducerB1, reducerB2 }))
NOTE: This does break with the idea that the reducer will always provide the same output given the same inputs. It would probably be better to accept the list of keys when creating the reducer:
const filterReducer2 = (reducer, keys) => {
let lastState = undefined;
return (state, action) => {
if (lastState === undefined || state == undefined) {
lastState = reducer(state, action);
return lastState;
}
var filteredState = {};
keys.forEach( (key) => {
filteredState[key] = state[key];
});
return lastState = reducer(filteredState, action);
};
}
const reducerA = filterReducer2(
combineReducers({ reducerA1, reducerA2 }),
['reducerA1', 'reducerA2'])
const reducerB = filterReducer2(
combineReducers({ reducerB1, reducerB2 }),
['reducerB1', 'reducerB2'])
OK, although the problem was already solved in the meantime, I just wanted to share what solution I came up:
import { ActionTypes } from 'redux/lib/createStore'
const mergeReducers = (...reducers) => {
const filter = (state, keys) => (
state !== undefined && keys.length ?
keys.reduce((result, key) => {
result[key] = state[key];
return result;
}, {}) :
state
);
let mapping = null;
return (state, action) => {
if (action && action.type == ActionTypes.INIT) {
// Create the mapping information ..
mapping = reducers.map(
reducer => Object.keys(reducer(undefined, action))
);
}
return reducers.reduce((next, reducer, idx) => {
const filteredState = filter(next, mapping[idx]);
const resultingState = reducer(filteredState, action);
return filteredState !== resultingState ?
{...next, ...resultingState} :
next;
}, state);
};
};
Previous Answer:
In order to chain an array of reducers, the following function can be used:
const combineFlat = (reducers) => (state, action) => reducers.reduce((newState, reducer) => reducer(newState, action), state));
In order to combine multiple reducers, simply use it as follows:
const combinedAB = combineFlat([reducerA, reducerB]);
Solution for those using Immutable
The solutions above don't handle immutable stores, which is what I needed when I stumbled upon this question. Here is a solution I came up with, hopefully it can help someone else out.
import { fromJS, Map } from 'immutable';
import { combineReducers } from 'redux-immutable';
const flatCombineReducers = reducers => {
return (previousState, action) => {
if (!previousState) {
return reducers.reduce(
(state = {}, reducer) =>
fromJS({ ...fromJS(state).toJS(), ...reducer(previousState, action).toJS() }),
{},
);
}
const combinedReducers = combineReducers(reducers);
const combinedPreviousState = fromJS(
reducers.reduce(
(accumulatedPreviousStateDictionary, reducer, reducerIndex) => ({
...accumulatedPreviousStateDictionary,
[reducerIndex]: previousState,
}),
{},
),
);
const combinedState = combinedReducers(combinedPreviousState, action).toJS();
const isStateEqualToPreviousState = state =>
Object.values(combinedPreviousState.toJS()).filter(previousStateForComparison =>
Map(fromJS(previousStateForComparison)).equals(Map(fromJS(state))),
).length > 0;
const newState = Object.values(combinedState).reduce(
(accumulatedState, state) =>
isStateEqualToPreviousState(state)
? {
...state,
...accumulatedState,
}
: {
...accumulatedState,
...state,
},
{},
);
return fromJS(newState);
};
};
const mergeReducers = (...reducers) => flatCombineReducers(reducers);
export default mergeReducers;
This is then called this way:
mergeReducers(reducerA, reducerB)
It produces no errors. I am basically returning the flattened output of the redux-immutable combineReducers function.
I have also released this as an npm package here: redux-immutable-merge-reducers.
There is also combinedReduction reducer utility
const reducer = combinedReduction(
migrations.reducer,
{
session: session.reducer,
entities: {
users: users.reducer,
},
},
);
What is "let x= something1 => something2 => something3" ?
I have this code and I'm failing to understand what does it do.
const myReducers = {person, hoursWorked};
const combineReducers = reducers => (state = {}, action) => {
return Object.keys(reducers).reduce((nextState, key) => {
nextState[key] = reducers[key](state[key], action);
return nextState;
}, {});
};
The full code incase you need:
//Redux-Style Reducer
const person = (state = {}, action) => {
switch(action.type){
case 'ADD_INFO':
return Object.assign({}, state, action.payload)
default:
return state;
}
}
const infoAction = {type: 'ADD_INFO', payload: {name: 'Brian', framework: 'Angular'}}
const anotherPersonInfo = person(undefined, infoAction);
console.log('***REDUX STYLE PERSON***: ', anotherPersonInfo);
//Add another reducer
const hoursWorked = (state = 0, action) => {
switch(action.type){
case 'ADD_HOUR':
return state + 1;
case 'SUBTRACT_HOUR':
return state - 1;
default:
return state;
}
}
//Combine Reducers Refresher
****HERE****
****HERE****
****HERE****
const myReducers = {person, hoursWorked};
const combineReducers = reducers => (state = {}, action) => {
return Object.keys(reducers).reduce((nextState, key) => {
nextState[key] = reducers[key](state[key], action);
return nextState;
}, {});
};
****
****
/*
This gets us most of the way there, but really want we want is for the value of firstState and secondState to accumulate
as actions are dispatched over time. Luckily, RxJS offers the perfect operator for this scenario., to be discussed in next lesson.
*/
const rootReducer = combineReducers(myReducers);
const firstState = rootReducer(undefined, {type: 'ADD_INFO', payload: {name: 'Brian'}});
const secondState = rootReducer({hoursWorked: 10, person: {name: 'Joe'}}, {type: 'ADD_HOUR'});
console.log('***FIRST STATE***:', firstState);
console.log('***SECOND STATE***:', secondState);
From: https://gist.github.com/btroncone/a6e4347326749f938510
let x= something1 => something2 => something3 is almost same as the following:
let x = function (something) {
return function (something2) {
return something3
}
}
The only difference is, arrows have lexical binding of this, i.e. binding in compile time.
An arrow function is
someParameters => someExpression
So, what is
someParameters => someThing => someThingElse
???
Well, by simple stupid "pattern matching", it's an arrow function, whose body (someExpression) is
someThing => someThingElse
In other words, it's
someParameters => someOtherParameters => someExpression
There's nothing special about this. Functions are objects, they can be returned from functions, no matter if those functions are written using arrows or the function keyword.
The only thing you really need to know to read this properly is that the arrow is right-associative, IOW that
a => b => c === a => (b => c)
Note: An arrow function can also have a body consisting of statements as well as a single expression. I was specifically referring to the form the OP is confused about.