Nick
Nick

Reputation: 2559

Populate Redux Reducer with Parameter Passed Via an Action

I'm currently trying to pass a dynamic ID into my redux reducer via an action. I can pull this ID all the way through into my actions, but I'm struggling on the last step, which is adding the value into my redux store.

This is the code I have so far, and would really appreciate any help!

Component: This passes my docDeleteId through to my modalDocDeleteAction

<Icon iconType="delete" onClick={() => modalDocDeleteAction(document.documentId)}/>

const mapDispatchToProps = dispatch => ({
    modalDocDeleteAction: docDeleteId =>
        dispatch(modalDocDeleteAction(docDeleteId))
});

export default connect(
    null,
    mapDispatchToProps
)(Results);

Action: Funky dispatch due to Thunk and reduxMulti middleware

export function modalDocDeleteAction(docDeleteId) {
    console.log(docDeleteId); // ID is retrieved successfully
    return dispatch => {
        dispatch([{ type: MODAL_DOC_DELETE }, modalOpenAction()]);
    };
}

Reducer:

case "MODAL_DOC_DELETE":
        return {
            ...state,
            modalTitle: "Delete Document?",
            modalText:
                    "Deleting a document will permanently remove it from S3",
            closeText: "No, Keep Document",
            continueText: "Yes, Delete Document",
            docDeleteId: !!!ID GOES HERE!!!
        };

I'd like the docDeleteId parameter passed through my action to populate my reducer. I'm struggling to find anything online that says this is possible, but I need the ID available for use elsewhere so I'm really hoping it is!!

Any help with this would be great! Thanks a lot!

Upvotes: 1

Views: 141

Answers (1)

Omair Nabiel
Omair Nabiel

Reputation: 1682

What we normally do is pass custom data in payload keyword to the reducer. Editing your code a little like this

export function modalDocDeleteAction(docDeleteId) {
    console.log(docDeleteId); // ID is retrieved successfully
    return dispatch => {
        dispatch([{ type: MODAL_DOC_DELETE, payload: docDeleteID }, modalOpenAction()]);
    };
}

and then in your reducer you'll access it as below

case "MODAL_DOC_DELETE":
        return {
            ...state,
            modalTitle: "Delete Document?",
            modalText:
                    "Deleting a document will permanently remove it from S3",
            closeText: "No, Keep Document",
            continueText: "Yes, Delete Document",
            docDeleteId: action.payload
        };

Upvotes: 2

Related Questions