loliki
loliki

Reputation: 957

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.

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));
}

Upvotes: 0

Views: 485

Answers (1)

giankotarola
giankotarola

Reputation: 775

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));
}

Upvotes: 1

Related Questions