Redux - how to save and update a key / value pair

I am using redux wth reactjs.

I want to store simple key / value pairs, but cannot get the reducer syntax correctly.

In this case, each key / value pair will maintain a connection to an external system.

Is this right to do? I start with reduction, so this is a bit of a mystery.

export default (state = {}, action) => { switch(action.type) { case 'addConnection': return { connections: { ...state.connections, { action.compositeKey: action.connection } } default: return state } } 
+5
source share
2 answers

You have only two errors with {} instead of [] and forget to use Object.assign .

 const reducer = (state = {}, action) => { switch (action.type) { case 'addConnection': return Object.assign({}, state, { connections: [ ...state.connections, { [actions.compositeKey]: action.connection } ] }); default: return state; } } export default reducer; 

This can help to see how this is expressed. He does the same, but I think he reads a little nicer

 const reducer = (state = {}, {type, compositeKey, connection}) => { switch (type) { case 'addConnection': return Object.assign({}, state, { connections: state.connections.concat({ [compositeKey]: connection }) }); default: return state; } } export default reducer; 

Or if you are using Immutable , something like this

 import Immutable from 'immutable'; const reducer = (state = Immutable.Map(), {type, compositeKey, connection}) => { switch (type) { case 'addConnection': return state.set( 'connections', state.get('connections').concat({ [compositeKey]: connection }) ); default: return state; } } export default reducer; 
+5
source

It can work

 const reducer = (state = {}, {type, compositeKey, connection}) => { switch (type) { case 'addConnection': var newData={}; newData[compositeKey]=connection; return Object.assign({}, state, newData) }); default: return state; } } export default reducer; 
+1
source

Source: https://habr.com/ru/post/1243031/


All Articles