0

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

1 Answer 1

1

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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

but the functions are defined by you, right?
maybe you may want to check if the FN_TO_CALL object has the field for the current optionTitle : if (FN_TO_CALL[optionTitle]) { FN_TO_CALL[optionTitle](cardIndex) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.