Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redux - how to store and update a key/value pair

I am using redux wth reactjs.

I want to store simple key/value pairs but can't get the reducer syntax right.

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

Is this the right way to do it? I'm at the beginning with redux so it's a bit of mystery.

export default (state = {}, action) => {
  switch(action.type) {
    case 'addConnection':
      return    {
        connections: {
          ...state.connections, {
          action.compositeKey: action.connection
        }
      }

    default:
      return state
  }
}
like image 278
Duke Dougal Avatar asked Feb 15 '16 07:02

Duke Dougal


People also ask

How do I update Redux state value?

The only way to update a state inside a store is to dispatch an action and define a reducer function to perform tasks based on the given actions. Once dispatched, the action goes inside the reducer functions which performs the tasks and return the updated state to the store. This is what Redux is all about.

How do you store data in the Redux store?

A store is a state container which holds the application's state. Redux can have only a single store in your application. Whenever a store is created in Redux, you need to specify the reducer. A reducer is a function that returns the next state of app.

Should I keep all component's state in Redux store?

Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component's internal state. Using local component state is fine.

How do I use Redux to update components?

When you use mapStateToProps() with the Redux connect() HOC, you are mapping your Redux state to your component through its props, so in your case this. props. language will update when the Redux stored updates.


1 Answers

This worked for me:

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

From the docs:

https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#correct-approach-copying-all-levels-of-nested-data

like image 108
Mjsnoop Avatar answered Sep 30 '22 05:09

Mjsnoop