Unable to access component properties through react-redux

Context: A React Native application utilizing Redux for managing complexity.

Versions:

  • typescript v3.0.3
  • react-native v0.56.0
  • redux v4.0.0
  • @types/react-redux v6.0.9
  • @types/redux v3.6.0

Issue: The main JSX component in my app is unable to access properties (errors detailed in comments).

The primary file:

//app.tsx
export default class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <MainRedux ownProp="as"/> //[1]: Type '{ ownProp: string; }' is not assignable to type 'Readonly<AllProps>'. Property 'appPermissions' is missing in type '{ ownProp: string; }'.
      </Provider>
    );
  }
}

and the secondary file:

//MainRedux.tsx
export interface ApplicationState { //originally in another file
  appPermissions: AppPermissionsState;
  //...
}

type StateProps = ApplicationState; //alias appPermissions is in the Application State

interface DispatchProps {
  getPermissions: typeof getPermissions;
  //...
}

interface OwnProps {
  ownProp: string;
}

type AllProps = StateProps & DispatchProps & OwnProps;

export class MainRedux extends React.Component<AllProps> {
  constructor(props: AllProps) {
    super(props);
    props.getPermissions(); //[2]: TypeError: undefined is not a function (evaluating 'props.getPermissions()')
  }
  //...
} //class

//...
const mapStateToProps: MapStateToProps<
  StateProps,
  OwnProps,
  ApplicationState
> = (state: ApplicationState, ownProps: OwnProps): StateProps => {
  return state;
};

const mapDispatchToProps: MapDispatchToPropsFunction<
  DispatchProps,
  OwnProps
> = (dispatch: Dispatch<AnyAction>, ownProps: OwnProps): DispatchProps => ({
  getPermissions: bindActionCreators(getPermissions, dispatch)
  //...
});

export default connect<StateProps, DispatchProps, OwnProps, ApplicationState>(
  mapStateToProps,
  mapDispatchToProps
)(MainRedux);

Error [1] occurs during compilation, while error [2] is a runtime issue.

Seeking assistance on identifying the problems. Appreciate your help.

Edit: Added debug information into mapStateToProps and mapDispatchToProps, but it seems like connect is not calling them. There's a possibility that even the connect function itself is not being triggered.

Answer №1

Looks like the state to props mapping may need some adjustments.

To test this, you can add the following code to your MapStateToProps function:

const mapStateToProps: MapStateToProps<StateProps,OwnProps,ApplicationState> = 
(state: ApplicationState, ownProps: OwnProps): StateProps => {
  return {test : "hello"}
};

Check if you can see test in your console.log(this.props) within your componentDidMount().

If it works, you will need to map your object keys accordingly:

return {
 propkey1 : state.propkey1,
 propkey2 : state.propkey2
 .... etc
}

However, without seeing the full codebase, it's difficult to provide a definitive solution.

Answer №2

Upon reading @MattMcCutchen's comment, it struck me. The connect function actually returns a decorated class that is no longer the original component class. For example, instead of MyComponent, it becomes something entirely different like

let ConnectedMyCommponent = connect(...)
. This new class can then be imported as
import {ConnectedMyComponent} from '.\...'
within the file containing the parent Provider tag, such as
<Provider><ConnectedMyComponent></Provider>
.

My mistake lies in not updating the import statement during code refactoring, where I neglected to change from import {MainRedux} from './...' to import MainRedux from './...'.

A helpful tip for those transitioning from vanilla react-native to redux react-native: remember to remove any export keywords from your component class definition, as connect will handle the creation of a new class. This simple adjustment can save you from spending too much time deciphering confusing error messages.

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

Angular is having trouble with the toggle menu button in the Bootstrap template

I recently integrated this template into my Angular project, which you can view at [. I copied the entire template code into my home.component.html file; everything seems to be working fine as the CSS is loading correctly and the layout matches the origina ...

React fails to acknowledge union types

I have the following types defined: export enum LayersItemOptionsEnum { OPERATOR, HEADER, } type sharedTypes = { children: string | ReactElement; }; type LayersItemStatic = sharedTypes & { label: string; option: LayersItemOptionsEnum; }; t ...

Encountering an issue with React Redux and Typescript involving the AnyAction error while working on implementing

While integrating redux-persist into my React project, I encountered an error. Previously, Redux was working smoothly, but upon the addition of redux-persist, I started receiving this error message: Types of property 'dispatch' are incompatib ...

Prevent the event listener from continuously triggering

I have a situation where every time I create an Angular component, an event listener is added. However, upon leaving the page and returning to it, a new event listener is added because the constructor is called again. The problem arises when this event is ...

Is it possible to declare two global variables with the same name in Angular?

There are two global variables that come from different third-party files with the same name. Previously, I would use them like this: declare var someVar; But now, how can I use both of these variables? declare var someVar; declare var someVar; Is th ...

Implement Material-UI's built-in validation for form submission

I'm in the process of setting up a form with validation: import React from 'react'; import { useForm } from "react-hook-form"; import axios, {AxiosResponse} from "axios"; import {Box, Button, Container, Grid, Typography} ...

Angular4 allows for the creation of a div that can horizontally scroll

Below is the HTML code I am working with: <div class="card-deck" fxLayout.xs="row" style="overflow: scroll; height:100%"> <md-card style="width:10rem" *ngFor="let make of filteredMakes" (click)="goToModels(make.niceName)" class=" ...

React Native's npm start seems to freeze at the "Starting Packager" stage

Having an issue with my react native app created using create-react-native-app. Initially, npm start was running smoothly. However, now it gets stuck at Starting Packager. A couple of days ago, I tried deleting the node_modules folder and reinstalling npm ...

What could be causing Highlight.js to fail to work following a redirect?

After developing a small application to address a specific issue, I encountered a problem while attempting to apply code highlighting using highlight.js. The issue arises when navigating from site1 to site2 or vice versa - the highlight does not take effec ...

Encountering a Typescript issue with the updated Apollo server version within a NestJS application

After upgrading my nestJS application to use version 3.2 of apollo-server-plugin-base, I encountered two TypeScript errors related to a simple nestJS plugin: import { Plugin } from '@nestjs/graphql' import { ApolloServerPlugin, GraphQLRequest ...

Can you guide me on how to programmatically set an option in an Angular 5 Material Select dropdown (mat-select) using typescript code?

I am currently working on implementing an Angular 5 Material Data Table with two filter options. One filter is a text input, while the other is a dropdown selection to filter based on a specific field value. The dropdown is implemented using a "mat-select" ...

Incorporating a Component with lazy-loading capabilities into the HTML of another Component in Angular 2+

Striving to incorporate lazy loading in Angular 2, I have successfully implemented lazy loading by following this helpful guide. Within my application, I have two components - home1 and home2. Home1 showcases the top news section, while home2 is dedicated ...

Exploring Composite Types with TypeScript's `infer` Keyword

After implementing redux in my project, I found myself including the following code snippet in my store: type CombinedParamTypes<T extends { [key: string]: (state: any, action: any) => any; }> = T extends { [key: string]: (state: infer R, ...

An issue where the keyboard disappears after entering just one character in a TextInput located within the header of a Flatlist

After spending two days working on this issue, I have identified a problem: When I placed a TextInput inside a Flatlist, the behavior of the TextInput changed - the keyboard loses focus after every character is typed. Version: React-native: 0.63.2 react: ...

What are the best methods for resizing a video without altering its aspect ratio?

function initializeConstructor(props) { super(props); this.state = { screenWidth: Dimensions.get('window').width, heightScaled: null, }; } <View style={styles.videoView}> <Video sourc ...

Tips for implementing a multi-layered accumulation system with the reduce function

Consider the following scenario: const elements = [ { fieldA: true }, { fieldB: true }, { fieldA: true, fieldB: true }, { fieldB: true }, { fieldB: true }, ]; const [withFieldA, withoutFieldA] = elements.reduce( (acc, entry) => ...

The local storage gets wiped clean whenever I am using this.router.navigate

I am in the process of building a website using Angular 5 and Typescript. One important aspect of my implementation is utilizing localStorage to store the JWT Token for user login. Whenever I click on a link (either Home or any other link), I implement a ...

Is there a way to add zeros at the beginning of ZIP codes that have only 3 or 4 digits using LODASH or Typescript?

Looking at the JSON data below, it includes information on USPS cities, states, counties, latitude, longitude, and zip codes. With over 349,000 lines of data, it's very extensive. ... { "zip_code": 988, "latitude": 18.39 ...

I possess multiple checkboxes that appear as described below. I am looking to modify the nested value highlighted in the blue circle in the image

I need to make a change in this area of my state: view screenshot The specific portion highlighted in the circle is what I want to modify **Here is my checkbox input code:** {this.state.data.map((elm) => ( <div className={classes.rowContainer}&g ...

Determine the dynamic height of content in a TypeScript file

Could you please provide guidance on obtaining the height of the content within this particular div element? For example, I need to calculate the dynamic height of the content. code .html <div class="margin-top-47 margin-horizontal-10" #hel ...