Skip to content

More on reusability for custom components. #1850

Closed
@sassanh

Description

@sassanh

Suppose that I'm trying to publish a react component to be used in redux applications. I want the react component to be stateless and keep its state in redux. Suppose that my component consists of an actions.js, a reducer.js and an index.jsx for example. The developer who wants to use it combine its reducer in some part of his redux store via combineReducers provided by redux (or redux-immutable). Then when an action gets dispatched the reducer perfectly changes the relevant part of state in store. So good so far. But what if the the developer wants to use it multiple times?

Suppose that the component is named Component and this is the desired component tree of the developer:

Container-1
|
|--Container-2
| |
| |--Component
| |
| |--OtherComponent-1
|
|--Component
|
|--OtherComponent-2

And suppose that Container-1 combines reducers of Container-2, Component and OtherComponent-2 and Container-2 combines reducers of Component and OhterComponent-1.

Now when an action from actions.js is dispatched, both reducers will apply it to their state (if developer doesn't do anything to prevent it.)

Currently I'm solving this by providing an elementId field in my actions related to reusable components and providing the same elementId field in initial state for relevant parts of state. For example my initial state for above configuration would be like this:

{
    "container-1": {
        "component": {
            "elementId": "topRightCornerAvatar",
            ...
        },
        "other-component": {...}
    },
    "component": {
        "elementId": "topLeftCornerAvatar",
        ...
    },
    "other-component-2": {...}
}

Then I check if the elementId provided in action matches the elementId of the state in the beginning of the reducer function. This way the action only affects desired instance of element.

It'd be great if we could have some utilities provided in redux for this purpose. For example combineReducer can take these elementId-s (or whatever else) and check it automatically when it receives an action and ignore the action if its elementId doesn't match. It can do it only if the elementId is provided.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions