0

I have an React/Redux app that works with "handlers" stored in Redux store and React components that are connectet to those handlers. These handlers are saved in a normalized flat structure and reffer to each other with unique id's.

What I want to do is to update a react element whenever any of his descendants update it's model in store.

// Redux state
const state = {
  h1: { name: "1", child: "h2" },
  h2: { name: "2", child: "h3" },
  h3: { name: "3", child: null }
};

// Helper function
const GetName = h => (h.child ? `${GetName(state[h.child])} in ${h.name}` : h.name);

// Component.jsx
class Handler extends React.Component {
  render = () => (
    <div>
      <div>Component {this.props.model.name} ({GetName(this.props.model))}</div>
      {this.props.model.child && <Handler id={this.props.model.child} />}
    </div>
  );
}

export default connect(
  Handler,
  (state, ownProps) => ({
    model: state[ownProps.id]
  })
);

Here is a simplified example of my code. The output here should look something like this:

Component 1 (3 in 2 in 1)
Component 2 (3 in 2)
Component 3 ()

In my code the GetName function is more complex, but the basic idea is that it builds the "name" of the handler. Now my proble is that f.e. when I update the third handler the first handler's name does not update since react didn't update it's component.

Is there a way to tell react that that component should be updated whenever state of descending handlers is changed or is there other simpler way?

Maroš Beťko
  • 2,181
  • 2
  • 16
  • 42

1 Answers1

0

I would suggest to replace your GetName helper function with reselect selector. To make the reselect working here, you need to transform the recursion in your GetName helper into iteration first (e.g. something like this).

lavor
  • 1,787
  • 1
  • 14
  • 21