TypeScript and Redux mapDispatchToProps are not in sync

Below is my React component written in TypeScript:

import React from 'react';
import {connect, ConnectedProps} from 'react-redux';
import logo from './assets/logo.png';
// import { Counter } from './features/counter/Counter';
import './App.css';

import {IApplicationState} from './features/application/reducers';

const mapStateToProps = (application: IApplicationState) => {
  const applicationComposite = application.applicationComposite;

  return {applicationComposite};
}
const connector = connect(mapStateToProps);
type PropsFromRedux = ConnectedProps<typeof connector>

interface Props extends PropsFromRedux {};

class App extends React.Component<Props> {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <span>
            <span>Attractora </span>
            {this.props.applicationComposite && <span>{this.props.applicationComposite.content}</span>}
          </span>
        </header>
      </div>
    );
  }
}

export default connector(App);

I am encountering an issue where the value of applicationComposite is always undefined, despite having an initial state value set in the reducer.

Upon debugging, I discovered that

mapStateToProps(application: IApplicationState)
correctly receives the value of applicationComposite as
application.application.applicationComposite
. However, when I attempt to assign
applicationComposite = application.application.applicationComposite
, it throws the following error:

Property 'application' does not exist on type 'IApplicationState'.

I have followed a tutorial on manually typing connect, but I am unable to identify where I might be making a mistake.

UPDATE

This is how my root reducer looks like:

import {combineReducers} from 'redux';
import application from '../features/application/reducers';

const rootReducer = combineReducers({
  application,
});

export default rootReducer;

And here is my application reducer:

import { Dictionary } from '@reduxjs/toolkit';
import { ActionInterface } from '../generals';
import {
  FETCH_APPLICATION_COMPOSITE_SUCCESS,
  SET_CURRENT_APPLICATION_COMPONENT
} from './actions';

export interface IApplicationState {
  applicationComposite: any,
  currentApplicationComponent: string | null,
}

const INIT_STATE = {
  applicationComposite: {content: 'test_content'},
  currentApplicationComponent: null
}

export default (state=INIT_STATE, action: ActionInterface) => {
  switch(action.type) {
    case FETCH_APPLICATION_COMPOSITE_SUCCESS: {
      return {
        ...state,
        //@ts-ignore: Object is possibly 'undefined'
        applicationComposite: action.payload.applicationComposite
      }
    }
    case SET_CURRENT_APPLICATION_COMPONENT: {
      return {
        ...state,
        //@ts-ignore: Object is possibly 'undefined'
        currentApplicationComponent: action.payload.applicationComponent
      }
    }
    default: {
      return state;
    }
  }
}

Answer №1

It appears that you may be overlooking the need to use the root state type within your mapStateToProps function.

In Redux, the application is just a part of the overall state, meaning you cannot directly access the application state in the mapStateToProps() function. To remedy this, it's necessary to define a root state type that acts as a central hub for all states.

export interface IRootState {
    application: IApplicationState
}

const rootReducer = combineReducers<IRootState>({
  application,
});

const mapStateToProps = (rootState: IRootState) => {
  const applicationComposite = rootState.application.applicationComposite;

  return {applicationComposite};
}

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

Ways to define an interface that can accommodate various interfaces with a specific structure

I am in need of a function that can accept a parameter with interfaces having a specific structure. The parameter should be either a string hash or a string hash along with an attribute string hash, as shown below: { anotherHash: { a: 'a', ...

Material-UI Slide component is encountering an issue where it is unable to access the style property of an undefined variable

Recently, I incorporated Material-UI Slide into my project and I'm curious about why the code functions correctly when written in this manner: {selectedItem && selectedItem.modal && selectedItem.modal.body ? ( selectedItem.modal.body.map((section ...

TypeScript - Minimize redundancy when defining types for a class and its constructor arguments

Here is a class structure I am currently using: class Person { id?: string = uuid(); name: string; constructor(data: Person) { _.merge(this, data); } } The 'uuid' function generates an id and '_' refers to loda ...

Transform JSON into a TypeScript interface with a specialized Date method

Within my Angular 7 project, there is a Post Model defined as follows: export interface PostModel { id: number; created: Date; published: boolean; title: string; } I have implemented an Angular service method aimed at retrieving posts: public g ...

We're sorry, the request was blocked due to a missing Access-Control-Allow-Origin header

Recently, while working on a blog application with the front end in react + typescript and backend in go iris, I encountered an issue when trying to fetch blog content using a get request. The backend was running on localhost:5000 and the node at localhost ...

The file node_modules/@types/node/index.d.ts encountered an error with code TS1084, indicating that the 'reference' directive syntax used is invalid

Having some trouble with typescript compilation. Anyone else encountering this issue? node_modules/@types/node/index.d.ts(20,1): error TS1084: Invalid 'reference' directive syntax. Here is my tsconfig.json setup: { "compileOnSave" ...

Submitting an image blob to a database using the FormBuilder

I'm facing an issue with uploading a file blob into the same DB as my form. Here is my form: this.accForm = this.formBuilder.group({ team_leader: ['', Validators.required], hotel_name: ['', Validators.required], address: [&a ...

Tips for determining the defaultValue type in React.context usage

'use client'; import { useState, createContext, useMemo } from 'react'; type MessageStatus = 'default' | 'success' | 'error'; export type MessageProps = { type: MessageStatus; payload: string; }; ty ...

Karma is reporting an error with TypeScript, saying it cannot locate the variable 'exports'

Currently, I am in the process of mastering how to write Unit Test cases for an angular project coded in Typescript. To facilitate this, I have opted for utilizing Karma and Mocha. Below lays out the structure of the application: Project/ ├── app/ ...

What are the steps to create an object from an array?

Is it possible to create an object from an array in TypeScript? { A: {H: 10, W: 20, S: 30}} using the following data: [ { group: A, name: H, value: 10 }, { group: A, name: W, value: 20}, { group: A, name: S, value: 30} ] L ...

Tips for refreshing the modified toggle in angular2

I currently have a newsletter subscription that is initially set based on the newsletter I receive when the user logs in. However, when I toggle the newsletter option, I receive a "successfully updated" message but the newsletter remains set to false even ...

What steps can be taken to resolve the issue of receiving the error message "Invalid 'code' in request" from Discord OAuth2?

I'm in the process of developing an authentication application, but I keep encountering the error message Invalid "code" in request when attempting to obtain a refresh token from the code provided by Discord. Below is a snippet of my reques ...

Mastering Props Typing in React Using TypeScript

Currently, I am faced with the task of defining the following: interface MyCompProps { someAttr: number } Instead of having to explicitly list all the aria-* attributes I need upfront, I would like to simply use aria- and other normal HTML attributes ...

How to efficiently eliminate duplicates from an array list using React framework

Keeping the array name constant while duplicating and repeating this process only clutters the list. Appreciate your help. setListItems(contents.data); console.log(contents.data); ...

Set every attribute inside a Typescript interface as non-mandatory

I have defined an interface within my software: interface Asset { id: string; internal_id: string; usage: number; } This interface is a component of another interface named Post: interface Post { asset: Asset; } In addition, there is an interfa ...

Ionic - Smooth horizontal tab scrolling for sorted categories

Currently, we are developing a web/mobile application that includes horizontal scroll tabs to represent Categories. While this feature works well on mobile devices, it requires additional functionality for web browsers. Specifically, we need to add two arr ...

Needing to utilize the provide() function individually for every service in RC4

In Beta, my bootstrapping code was running smoothly as shown below: bootstrap(App, [ provide(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, helperService: HelperService, authProvider: AuthProvider) => new CustomHt ...

Using an array of references in React

I've encountered a problem where I'm trying to create a ref array from one component and then pass it to another inner component. However, simply passing them as props to the inner component doesn't work as it returns null. I attempted to fo ...

A loop in JavaScript/TypeScript that runs precisely once every minute

Here is a snippet of my code: async run(minutesToRun: number): Promise<void> { await authenticate(); await this.stock.fillArray(); await subscribeToInstrument(this, this.orderBookId); await subscribeToOrderbook(this, this.orderBookId ...

The close button in Angular 4 is unresponsive until the data finishes loading in the pop-up or table

Having trouble with the Close button in Angular 4 popup/table The Pop Up is not closing after clicking anywhere on the screen. I have added backdrop functionality so that the pop-up closes only when the user clicks on the close icon. However, the close i ...