Jeroen Berrevoets Jeroen Berrevoets - 1 month ago 17
React JSX Question

Level of Components listening to same redux state

My situation is as follows:

I have 1 field in my redux state that's nothing more than an object of following type:

{String, [{String, Float}]}
. This field in my state is used by 2 Components (who query over GraphQL using the
String
as a variable).

Both components are connected via the
connect
method (using decorator syntax).

@connect((state) => ({variable: state.variable.field}))
@graphql(QUERY, {...})
export default class Component1 extends React.Component { ... }


@connect((state) => ({variable: state.variable.field}))
@graphql(QUERY, {...})
export default class Component2 extends React.Component { ... }


Nothing special since this works for every other
Component
. Yet, when I call these components on the same level while logging the state in their
render
methods:

<div>
<Component1 />
<Component2 />
</div>


The
Component1
logs the state as is,
Component2
logs the initial state. When I switch the components in place:

<div>
<Component2 />
<Component1 />
</div>


The opposite happens:
Component2
logs the correct state,
Component1
doesn't.

When I call either one of the components inside each other (where
Component1
calls
Component2
as part of their render), everything is fine.

I'm not sure what is going on here, nor can I find any documentation stating you shouldn't call 2 components listening to the same state on the same location.

Hope someone can help me understand what's going on

Answer

Usually this shouldn't be an issue. So maybe the issue is caused by your code? (Just a wild guess w/o seeing any actual code!)

But I would suggest to lift the connect to Redux into the parent component anyway. Especially if both components require the exact same part of the state.