So I've just refactored an app created in react using useContext/useReducer in order to manage the state better. I'm having a great time and have managed to get the dispatch function to work with bits you have to select.
HOWEVER. When it comes to conditionally rendering the start/stop button, I'm flummoxed. In my reducer function I have the following:
const redFunc = (state, action) => {
switch (action.type) {
case "play": {
return {
...state,
isPlaying: true,
};
}
case "stop": {
return {
...state,
isPlaying: false,
};
}
Which is passed down via React.createContext() to the components. The thing is, I don't really understand where to put the dispatch function in order to get isPlaying to actually change. Here is my start/stop button:
<input
id="on-off"
type="button"
value={isPlaying ? "stop" : "start"}
onClick={() => togglePlay()}
/>
So somewhere, I think I need to put this line of code in, as I understand it (please correct me if I'm wrong):
dispatch(isPlaying ? { type: "stop" } : { type: "start" });
Here it is in my togglePlay() function (which is definitely wrong as it doesn't work...):
const togglePlay = () => {
if (isPlaying) {
audioContextRef.current.suspend();
} else {
audioContextRef.current.resume();
}
dispatch(isPlaying ? { type: "stop" } : { type: "start" });
};
I feel like there's something fundamental I'm missing about the dispatch function but I can't figure it out, and I've spent SUCH a long time on it that I'm crying tears of Reacty sadness. Everything was wonderful when I could use useState()
...
Help...?