Having trouble dispatching a TypeScript action in a class-based component

I recently switched to using this boilerplate for my react project with TypeScript. I'm facing difficulty in configuring the correct type of actions as it was easier when I was working with JavaScript. Now, being new to TypeScript, I am struggling to figure out why my code is not functioning properly. Any insights on how to best resolve this issue would be greatly appreciated.

Dashboard.tsx

interface IAction{
  type: string,
  payload: any,
}

interface IProps {
  dashboard: any;
  changeUserName: IAction;
}
interface IState {}

class Dashboard extends React.Component<IProps, IState> {
  componentDidMount(){
    console.log("____FOCUS____");
    console.log(this.props);
    this.props.changeUserName("NewName");
    console.log("____FOCUS____");
  }
  render() {
    return (
      <>
        <Helmet>
          <title>Dashboard</title>
          <meta name="description" content="Description of Dashboard" />
        </Helmet>
        <DashboardComponent username={'somevalue'} />
      </>
    );
  }
}


const mapStateToProps = (state: any, ownProps: any) => ({
  dashbaord: selectDashboard(state),
});

const mapDispatchToProps = (dispatch: any, ownProps: any) => ({
  ...bindActionCreators({
    ...actions,
  }, dispatch),
});

const withConnect = connect(mapStateToProps, mapDispatchToProps);
const withReducer = injectReducer({key: sliceKey, reducer: dashboardReducer});
const withSaga = injectSaga({key: sliceKey, saga: dashboardSaga});

export default compose(
  withReducer,
  withConnect,
  withSaga,
)(Dashboard);

Types

The types I have defined align with the documentation.

/* --- STATE --- */
export interface DashboardState {
  username: string;
}

export type ContainerState = DashboardState;

Slice

I've created a slice according to the instructions provided in the documentation.

export const initialState: ContainerState = {
  username: 'Initial Username',
};

const dashboardSlice = createSlice({
  name: 'dashboard',
  initialState,
  reducers: {
    changeUserName(state, action: PayloadAction<string>) {
      state.username = action.payload;
    },
  },
});

export const { actions, reducer, name: sliceKey } = dashboardSlice;

Answer №1

Challenge

I realized that I wasn't creating interfaces in the correct way. Although my method of dispatching class based components remained the same, the issue was with the interfaces not being implemented correctly.

Solution Code

Dashboard.tsx

interface IProps {
  initChangeUserName: Function;
  changeUserName: Function;
}

interface IState {}

class Dashboard extends React.Component<IProps, IState> {
  render() {
    return (
      <>
        <Helmet>
          <title>Dashboard</title>
          <meta name="description" content="Description of Dashboard" />
        </Helmet>
        <DashboardComponent 
        username={'somevalue'}
        initChangeUserName={this.props.initChangeUserName}
        />
      </>
    );
  }
}

const mapStateToProps = (state: any, ownProps: any) => ({
  dashboard: selectDashboard(state),
});

const mapDispatchToProps = (dispatch: any, ownProps: any) => ({
  ...bindActionCreators({ ...actions }, dispatch),
});

const withConnect = connect(mapStateToProps, mapDispatchToProps);
const withReducer = injectReducer({ key: sliceKey, reducer: dashboardReducer });
const withSaga = injectSaga({ key: sliceKey, saga: dashboardSaga });

export default compose(
  withReducer,
  withConnect,
  withSaga,
)(Dashboard);

DashboardComponent.tsx


// ....
// This used to be a functional component
<UserNameForm initChangeUserName={props.initChangeUserName} />
// ....

UserNameForm.tsx

// ....
this.props.initChangeUserName(this.state.username);
// ....

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

Invoke cloud functions independently of waiting for a response

Attempting a clever workaround with cloud functions, but struggling to pinpoint the problem. Currently utilizing now.sh for hosting serverless functions and aiming to invoke one function from another. Let's assume there are two functions defined, fet ...

Unable to access contextual values in NextJS

When attempting to retrieve values from the context API, I am encountering issues where I receive a default value (without the updates made during the context call) and an undefined value (which should receive a value in the context provider). sortListCont ...

Leveraging NPM workspaces in combination with Expo and Typescript

I'm struggling to incorporate NPM 7 workspaces into a Typescript Expo project. The goal is to maintain the standard Expo structure, with the root App.tsx file, while segregating certain code sections into workspaces. I'm facing challenges compil ...

Adjusting Material UI styling with media queries to accommodate different container sizes

Upon reviewing the latest version of MUI, I have noticed that responsive breakpoints and other features are based on screen size. Currently, we are working on developing a dashboard as a reusable component. I am interested in utilizing the default Materia ...

What is the most efficient way to simultaneously check multiple variables for undefined values?

Before executing my code, I need to ensure that none of the variables in a given list are undefined. In the code snippet below, there are 4 variables with uncertain values. While I can manually check variables a and b to satisfy TypeScript's requirem ...

Encountered a React Proxy error: Unable to redirect request /api/ from localhost:3000 to http://localhost:5000 (ECONNREFUSED). Unfortunately, couldn't find any online solution for this issue

I've been struggling to connect my react frontend to the backend despite trying various methods. I added "proxy" : "localhost:5000" in my code, but still no luck. Additionally, I attempted the following: const { createProxyMiddleware } = require(&apo ...

Develop a novel object framework by merging correlated data with identical keys

I am trying to organize the related data IOrderData by grouping them based on the productId and brandId. This will help create a new array of objects called IOrderTypeData, where the only difference between the objects is the delivery type. Each product id ...

I am looking to apply the flex-direction style to the Material UI Grid component

Looking to set the direction property for a <Grid container> component in the Material UI framework. After reviewing the documentation, I attempted setting the direction property as column with the following code snippet: <Grid container directio ...

Encountering a "Object.fromEntries is not a function" error while implementing chakra-ui with next.js

After creating a next.js app using Vercel, I decided to add chakra-ui by running the following command: npm i @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^4 Unfortunately, this resulted in an error message appearing: TypeError: ...

What is the best way to integrate an API call into the map function to dynamically render DOM elements?

I am currently facing an issue where I am trying to utilize a promise within my map method, but the output is appearing as [object Promise]. However, when I check the code where I created the promise, I return the desired response data using res.data.itemT ...

Guide to passing a dynamic value to a CSS class and customizing it in Material UI within a React application

Is it possible to create dynamic CSS by passing values from the className attribute? I am facing a situation where the left positions of a div need to change dynamically based on data in a React component. Here is the scenario, and I am curious if someth ...

Seeking a breakdown of fundamental Typescript/Javascript and RxJs code

Trying to make sense of rxjs has been a challenge for me, especially when looking at these specific lines of code: const dispatcher = fn => (...args) => appState.next(fn(...args)); const actionX = dispatcher(data =>({type: 'X', data})); ...

Centering Material UI Grid layout vertically on the page

I have been working with the material UI grid code below (taken from their documentation and modified to illustrate my current challenge): import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Paper fr ...

What is the process for obtaining a literal type from a class property when the class is passed as an argument, in order to use it as a computed property

Just a moment ago I posted this question on Stack Overflow, and now I have a follow-up query :) Take a look at this code snippet: import { ClassConstructor } from "class-transformer"; import { useQuery as useApolloQuery } from "@apollo/clie ...

"Once the queryParams have been updated, the ActivatedRoute.queryParams event is triggered once

Within my Angular component, I am making an API call by passing a hash string extracted from the current query parameters. Upon receiving the API result, a new hash is also obtained and set as the new hash query parameter. Subsequently, the next API call w ...

What is the method by which the Material-UI Button component determines the properties for the component that is passed to the `component` prop

Could someone please clarify how Material-UI enhances the properties of its Button component by incorporating the properties of a specific component if passed in the component attribute? interface MyLinkProps extends ButtonBaseProps { someRandomProp: str ...

Retrieving user input in React by utilizing the onChange event handler

I have been tasked with creating a Quiz App and I am currently working on building it. The app consists of several components such as "question", "question-list", and "add-question". Within the "add-question" component, there is a form that allows users ...

Error encountered while using Material-UI proptype classes

I keep getting this warning message in my console: index.js:2178 Warning: Failed prop type: The prop classes is required in WithStyles(Grid), but its value is undefined. I have double-checked to ensure that classes are passed as a prop correctly. However ...

Create an interactive Angular form that dynamically generates groups of form elements based on data pulled from

I am currently developing an Angular application and working on creating a dynamic form using Angular. In this project, I am attempting to divide the form into two sections: Person Name and Personal Details. While I have successfully grouped fields for P ...

Tips for implementing a JavaScript Material Design framework in ReScript code?

I am attempting to integrate the material-ui library into a Rescript/React application. The code snippet below demonstrates how to display a button: @module("@material-ui/core/Button") external button: string = "default" @react.compone ...