I’m working with the WordPress Interactivity API and I’ve encountered an issue with using context and getter methods. Here’s my current code:
import { store, getContext } from '@wordpress/interactivity';
const { state, actions } = store('content-quiz', {
state: {
get resultMessage() {
const context = getContext();
const isSolved = context.selectedAnswer === context.quiz.correctAnswer ? 1 : 0;
return isSolved ? 'Correct! Well done!' : 'Sorry, that's incorrect. Try again!';
}
},
actions: {
selectAnswer: (event) => {
const context = getContext();
context.isSubmitted = true;
context.selectedAnswer = event.target.value;
const isSolved = context.selectedAnswer === context.quiz.correctAnswer ? 1 : 0;
context.resultMessage = isSolved ? 'Correct! Well done!' : 'Sorry, that's incorrect. Try again!';
},
},
});
I’ve noticed that many examples mix state and context, even for non-global values. I prefer to use context exclusively for local values that don’t need to be shared. However, I’m facing some challenges:
The current implementation uses state for resultMessage, which I believe should be a local value in context.
I want to use a getter method within the context property, similar to how it’s used in state.
I’ve tried the following approach, but it doesn’t work:
store('content-quiz', {
context: {
get resultMessage() {
// return ...
}
}
});