Search code examples
reactjsreduxreact-reduxnormalizr

redux, normalizr, access store mapDispatchToProps


If I have a data object like below

 {
   items: [
     {id: 1, selected: false},
     {id: 2, selected: false}
   ]
 }

Running this through the normalizr would get me something like

{
  entities: {
    1: {selected: false},
    2: {selected: false}
  },
  result: {
    items: [1, 2]
  }
}

Typically I would have an Items component that maps the state to props like this:

const mapStateToProps = (state) => {
  return state.result;
};

The problem I have is on the Items component, I would have a save button that needs to send the state of the store to the server.

I haven't seem to be able to find a good way to access the store to denormalize the data before sending it to the server.

1) I prefer not to include the Entities in MapStateToProps because there is no need for the items component to know about it.

2) MergeProps also seems suboptimal due to performance issues.

Right now I'm accessing the store directly by simply importing the store and accessing it in my dispatch methods which seems to work, but that breaks the separation of concern, is there a better way to do this?


Solution

  • Judging from the description of your problem, I believe you send the store's data by a method inside Save button component, or another React component. If you do that, you must expose the sending data to that component no matter what.

    An alternative solution is to handle the API call by a middleware. Libraries such as redux-saga or redux-thunk can handle your case neatly. They are designed to handle async flows, and provide access to the store.