2

Creating a container component by connect() function with defined mapStateToProps gives access to state (store.getState()) of entire tree state.

For example, I have combined state tree:

{
  loaded: true,
  threads: [
    {
      id: 1,
      title: "Thread 1",
      messages: [
        { 
          id: 1, 
          text: "Message 1"
        }        
      ]
    },
    {
      id: 1,
      title: "Thread 2",
      messages: [
        { 
          id: 2, 
          text: "Message 2"
        },
        { 
          id: 3, 
          text: "Message 3"
        }  
      ]
    }   
  ]
}

How should I access particulary messages of given thread?

const mapStateToProps = (state) => {
  return {
    messages: getMessagesByThread(state.threads, <threadId>)
  }
}

In this case lets assume that I don't want to have 'activeThreadId' param in store state tree (store.getState().activeThreadId).

What is the best other possibility to provide threadId?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Rafał Łyczkowski
  • 995
  • 2
  • 11
  • 27

1 Answers1

1

If you have threadId as a prop on your component, you could pass it over via the ownProps param:

const mapStateToProps = (state, ownProps) => {
  return {
    messages: getMessagesByThread(state.threads, ownProps.threadId)
  }
}

This is the best way to go I think.

larrydahooster
  • 4,114
  • 4
  • 40
  • 47
  • Ok, but going deeper through the state tree will force me to provide more identifiers (key of each node) to access particulary object at lower level. – Rafał Łyczkowski Feb 16 '16 at 14:44
  • Yeah sure, but if you need a specific massage in your component, you could simply pick it from the messages prop? I mean if you want to access a single message from a thread you need to be aware of the full path anyways? – larrydahooster Feb 16 '16 at 16:32
  • True, Maybe I should not - just do now know it now. Should my reducers composition be simplier? Anyway, it's common use to combine reducers making state tree much more complex. – Rafał Łyczkowski Feb 16 '16 at 17:59
  • 1
    Yeah keeping the state-tree flat, makes the handling in the reducer much simpler. If you keep your messages beside your threads with a reference to the messages, it is easier. I recommend you to read this answer: http://stackoverflow.com/questions/32135779/updating-nested-data-in-redux-store/32921731#32921731 – larrydahooster Feb 16 '16 at 18:08