Currently, I am working on a project to enhance my understanding of Redux and Typescript. I am still navigating through the learning curve in this area.
Based on what I have learned from a book, I have established a "slice" that includes definitions for reducers:
const initialState: { value: Book[], formShown: boolean } = { value: [], formShown : false };
export const cartSlice = createSlice({
name : 'cart',
initialState : initialState,
reducers : {
addBookToCart : (state, action) => {
state.value.push(action.payload);
},
showForm: (state, action) => {
state.formShown = true;
}
}
});
The first reducer (addBookToCart) functions correctly, but the second one encounters an issue. Although it should not require any parameters since it only sets a boolean switch, I consistently face an error regardless of the input provided.
Here is the relevant code snippet:
const showForm = (e : React.MouseEvent<HTMLElement>) => {
e.preventDefault();
dispatch(showForm(true));
};
if (itemList.length) {
return (
<>
<ul>
{itemList}
</ul>
<p><b>Total Price: ${totalPrice.toFixed(2)}</b></p>
<br />
{
formShown ? <PaymentForm />
: <Button variant="success" onClick={showForm}>Checkout</Button>
}
</>
);
}
else {
return (<p><b>Your Shopping Cart is Empty</b></p>);
}
When compiling the code in the IDE, the following error immediately arises:
ERROR in src/Cart.tsx:64:18
TS2769: No overload matches this call.
Overload 1 of 3, '(thunkAction: ThunkAction<unknown, { page: { value: string; }; books: { value: Book[]; }; ajax: { value: string; }; cart: { value: Book[]; formShown: boolean; }; }, undefined, AnyAction>): unknown', gave the following error.
Argument of type 'void' is not assignable to parameter of type 'ThunkAction<unknown, { page: { value: string; }; books: { value: Book[]; }; ajax: { value: string; }; cart: { value: Book[]; formShown: boolean; }; }, undefined, AnyAction>'.
Overload 2 of 3, '(action: AnyAction): AnyAction', gave the following error.
Argument of type 'void' is not assignable to parameter of type 'AnyAction'.
Overload 3 of 3, '(action: AnyAction | ThunkAction<unknown, { page: { value: string; }; books: { value: Book[]; }; ajax: { value: string; }; cart: { value: Book[]; formShown: boolean; }; }, undefined, AnyAction>): unknown', gave the following error.
Argument of type 'void' is not assignable to parameter of type 'AnyAction | ThunkAction<unknown, { page: { value: string; }; books: { value: Book[]; }; ajax: { value: string; }; cart: { value: Book[]; formShown: boolean; }; }, undefined, AnyAction>'.
62 | const showForm = (e : React.MouseEvent<HTMLElement>) => {
63 | e.preventDefault();
> 64 | dispatch(showForm(true));
| ^^^^^^^^^^^^^^
65 | };
66 |
67 | if (itemList.length) {