im trying to set up usereducer and i want to be able to flip the state of hasStarted (a boolean). im new to typescript and cant seem to figure out how to correctly implement it. here's my code (theres probably all sorts of things wrong with this code, sory)
import React from "react";
const ACTIONS = {
FLIP: "flipHasStarted"
}
type State = {
hasStarted: boolean;
};
type Action = {
type: "flip";
};
const reducer = (state: State, action: Action) => {
switch (action.type) {
case ACTIONS.FLIP:
return {...state, hasStarted: !hasStarted}
}
return state;
};
const initialState = {
hasStarted: false,
};
export const App = () => {
const [state, dispatch] = React.useReducer(reducer, initialState);
return (
<>
<button onClick={() => dispatch(flipHasStarted)} className="bg-yellow-500 p-8">
TEST
</button>
</>
);
};
CodePudding user response:
There is a little confusion in your action definition, i fixed it like this:
import React from "react";
// Action types
const FLIP_ACTION = "FLIP_ACTION";
type ActionType = typeof FLIP_ACTION;
type Action = {
type: ActionType;
};
// Action creators
const flip = (): Action => ({
type: FLIP_ACTION,
});
// State
type State = {
hasStarted: boolean;
};
const initialState = {
hasStarted: false,
};
// Reducer
const reducer = (state: State, action: Action) => {
switch (action.type) {
case FLIP_ACTION:
return { ...state, hasStarted: !state.hasStarted };
default:
return state;
}
};
export const App = () => {
const [state, dispatch] = React.useReducer(reducer, initialState);
return (
<>
<button
onClick={() => dispatch(flip())}
className="bg-yellow-500 p-8"
>
TEST
</button>
</>
);
};
If you want to add more action, you have to do 4 things:
- define a new action type:
const SOME_ACTION = "SOME_ACTION";
- update
ActionType
definition
type ActionType = typeof FLIP_ACTION | typeof SOME_ACTION;
create an action creator (this is optional but it's makes action dispatch cleaner):
const someAction = (): Action => ({ type: SOME_ACTION, });
add a
case
in your reducer
Hope this helps
CodePudding user response:
as i can see,in your code the flipHasStarted is not defined,so you are supposed to give an action object to dispatch like this
<button onClick={() => dispatch({
type:ACTIONS.FLIP
})} className="bg-yellow-500 p-8">
TEST
</button>