Aerendir
Aerendir

Reputation: 6379

Redux: How to pass an ID to the mapStateToProps function to get from the state an entity with that ID

I have this container component:

const TodoListContainer = connect(mapStateToProps, mapDispatchToProps)(TodoListComponent)

I call it in this way:

    let TodoListHtml = document.getElementById('TodoList');

    render(
        <Provider store={store}>
            <TodoListContainer id={TodoListHtml.dataset.id}/>
        </Provider>,
        TodoListHtml
    )

As you can see I pass the container the prop id=TodoListHtml.dataset.id that is the ID of the list I'd like to render.

My state is shaped this way:

state {
    TodoLists: {
        entities: {
            1: {
                id: 1,
                name: 'The name of the list'
            }
        }
    }
}

So, my container component should get from the state the TodoList state.TodoLists.entities.1

My pseudo-code:

// Container.js
const getTodoList = (state, id) => {
    return state.TodoLists.entities.1
}

const mapStateToProps = (state, id) => {
    return {
        todoList: getTodoList(state, id)
    }
}

export default const TodoListContainer = connect(mapStateToProps)(TodoListComponent)

And this is the code that renders the container component

// Todolist.html: The html calling the container component
let TodoListHtml = document.getElementById('TodoList');

render(
    <Provider store={store}>
        <TodoListContainer id={TodoListHtml.dataset.id}/>
    </Provider>,
    TodoListHtml
)

The question is: how can I pass the ID?

Upvotes: 4

Views: 1202

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281626

MapStateToProps takes ownProps as the second argument, you would pass the id a props to the Container component and then you do get it like

const mapStateToProps = (state, ownProps) => {
    return {
        todoList: getTodoList(state, ownProps.id)
    }
}

Upvotes: 4

Related Questions