Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Redux, dispatch dynamic function

I’m building a fairly big application that is using Redux and GraphQL.

I have a room with multiple options, the user can choose from. In order to not repeat the code or have a switch case statement, as the options will always be dynamic, I want to dispatch a dynamically called function.

Here is a summary of my code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const test = (optionTitle, cardIndex) => {
    dispatch(changeKitchenFront(cardIndex));
}

Here is where this is being triggerend, the cardTitle in this case is dynamic based on what element was clicked.

<div key={index} onClick={() => test(cardTitle, index)}>
  ...rest of the code
</div>

I tried to do it like this, but it doesn’t work:

const test = (optionTitle, cardIndex) => {
    dispatch(changeKitchen{$optionTitle}(cardIndex));
}

>Solution :

Maybe you may want to have an object that contains the right key with it right function, like:

const FN_TO_CALL = {
 front: changeKitchenFront,
 back: changeKitchenBack,
}

then in the test function:

const test = (optionTitle, cardIndex) => {
    dispatch(FN_TO_CALL[optionTitle](cardIndex));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading