Issue encountered while attempting to utilize a basic redux reducer to define a boolean value, regarding a mismatch in overrides

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) {

Answer №1

The Function of showForm serves as both an event handler callback function and an action within the codebase. The color highlighting in this excerpt indicates that the showForm action may not have been properly exported, leading to its absence in the component utilizing it.

When invoking the showForm action, no arguments are required. It is possible to eliminate the action parameter from the showForm reducer. Therefore, updating showForm can be achieved by implementing the following:

showForm: (state) => {
    state.formShown = true;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Save the ID values of selected users in Angular Mentions feature

Using the angular mentions library, I successfully incorporated a textarea that enables me to mention multiple users. Is there a method to store the IDs of the selected users? Ideally, I would like to save them as an array of strings. For instance: If I ...

Exploring the best practices for integrating Bootstrap into a Webpack and Angular2 project

I am looking to incorporate Bootstrap into my Angular2 project, including both the CSS and JS files. What is the best way to include these files in the project to ensure webpack functions properly? In the previous version using systemjs, it was included i ...

Angular - Ensuring service completion before proceeding with navigation

I'm currently facing an issue where I need to populate data in a service before navigating, but the navigation is happening before the data is ready. Here's the code in my service: addToken(token) { this.cookieService.set( 'token', ...

The property "__esModule" is read-only and cannot be assigned to

While compiling a React and Redux application using Webpack and Babel, I encounter the following error: Uncaught TypeError: Cannot assign to read only property '__esModule' of #<Object> This issue arises in some older browsers (such as Ch ...

Removing a dynamic TypeScript object key was successful

In TypeScript, there is a straightforward method to clone an object: const duplicate = {...original} You can also clone and update properties like this: const updatedDuplicate = {...original, property: 'value'} For instance, consider the foll ...

Debugging with Typescript in Visual Studio Code

I attempted to use the solution found here: how to debug typescript files in visual studio code However, when I set a breakpoint in my .ts files, the debugger indicates that the file is not found. Oddly enough, breakpoints in the .js files are working fin ...

Incorporating TypeScript with jQuery for efficient AJAX operations

I recently added jQuery typings to my TypeScript project. I am able to type $.ajax(...) without encountering any compile errors in VS Code. However, when I test it on localhost, I receive an error stating that "$ is not defined." In an attempt to address t ...

What causes the error "property does not exist on type" when using object destructuring?

Why am I encountering an error in TypeScript when using Object destructuring? The JavaScript code executes without any issues, but TypeScript is showing errors. fn error: This expression is not callable. Not all elements of type '(() => void) | ...

Unable to bind to ngModel as it returned as "undefined" in Angular 8

Whenever I bind a property to ngModel, it consistently returns undefined <div> <input type="radio" name="input-alumni" id="input-alumni-2" value="true" [(ngModel) ...

What is the process of declaring a react-icons icon in TypeScript?

Having a dilemma with declaring the icon in my array that contains name and icon. export const SidebarMenuList: SidebarMenu[] = [ { name: "Discover", icon: <AiOutlineHome />, id: SidebarCategory.Discover, }, ] The SidebarMe ...

TypeScript does not recognize the $.ajax function

Looking for help with this code snippet: $.ajax({ url: modal.href, dataType: 'json', type: 'POST', data: modal.$form.serializeArray() }) .done(onSubmitDone) .fail(onSubmitFail); ...

Error: Could not find module: Unable to locate 'rxjs/add/observable/throw' in 'D:AngularhttpErrorHandlingExamplesrcapp'

I'm working on an Angular project to practice error handling, but I encountered an issue when trying to import the 'throw' module. The error message reads as follows: Error Message: "ERROR in ./src/app/employee.service.ts Module not found: E ...

PhpStorm is unable to resolve the @ionic/angular module

I have encountered a peculiar issue with my Ionic v4 project. While the project runs smoothly, PhpStorm seems unable to locate my references to @ionic. https://i.stack.imgur.com/umFnj.png Interestingly, upon inspecting the code, I realized that it is act ...

Tips for utilizing the index and style attributes when passing them to the Row function in React-Window

Currently, I am attempting to define the index and style parameters passed to the Row function in TypeScript. //https://github.com/bvaughn/react-window import * as React from "react"; import styled from "styled-components"; import { Fi ...

Utilizing React and Typescript to create custom attributes

With React Typescript, it is possible to include custom data-* attributes. But the question arises, can we also add other custom attributes such as 'name' or 'test'? <span name="I'm causing a type error" data-test="I'm Wor ...

Techniques for a versatile class limited to a particular category

In my code, I have a Vector class that looks like this: class Vector<N extends number> {...} N represents the size or dimension of the vector. This Vector class also includes a cross product method to calculate the cross product between vectors: cro ...

Implementing a conditional chaining function in TypeScript

I'm currently facing an issue while implementing a set of chained functions. interface IAdvancedCalculator { add(value: number): this; subtract(value: number): this; divideBy(value: number): this; multiplyBy(value: number): this; calculate( ...

Utilizing TypeScript with Sequelize for the Repository Design Pattern

I am in the process of converting my Express API Template to TypeScript, and I am encountering difficulties with the repositories. In JavaScript, the approach would be like this: export default class BaseRepository { async all() { return th ...

Conceal object from inventory upon clicking

As someone who is new to React and Typescript, I am facing challenges in understanding how to hide a ticket from the list when the hide button is clicked. displayTickets = (tickets: Ticket[]) => { const filteredTickets = tickets.filter(t => ...

What steps can be taken to troubleshoot a TypeScript-powered Node.js application running in WebStorm?

Seeking advice on debugging a node.js application utilizing TypeScript within WebStorm - any tips? ...