Setting up TypeScript to use a connected component within a parent component: A step-by-step guide

I have created a connected component that utilizes mapStateToProps and mapDispatchToProps to inject the properties into the Props without the need for the parent to inject anything. However, TypeScript raises an error when I import it into another component.

Form.tsx:


type IProps = {
  insertError: boolean,
  cleanErrors: () => ICleanErrorsAction,
  addArticle: (arg0: IArticle) => IAddArticleAction
}

type IState = {
  title: string,
  [id:string]: string
}

class ConnectedForm extends Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);

    this.state = {
      title: ""
    };
  }

  render() {
    // some implementation

    return (
      <form onSubmit={this.handleSubmit}>
        // some implementation
      </form>
    );
  }
}

const mapDispatchToProps = (dispatch: any) => {
  return {
    addArticle: (article: IArticle) => addArticleAction(article),
    cleanErrors: () => cleanErrorsAction()
  };
}

const mapStateToProps = (state: IStore): any => {
  return state.errors.insertError
}


const Form = connect(mapStateToProps, mapDispatchToProps)(ConnectedForm);
export default Form;

When using <Form /> in the parent component, TypeScript throws the following error:

Type '{}' is missing the following properties from type 'Readonly<Pick<IProps, "insertError" | "cleanErrors" | "addArticle">>': insertError, cleanErrors, addArticle

I prefer not to make every field in Props optional just to avoid null checks...

The props are passed through the connect function, so there should be no need to pass them again. Any suggestions would be appreciated. Thanks.

Answer №1

It appears that your mapStateToProps function may need some adjustments. The key thing to remember is that this function should return an object with properties matching the props on the connected component. In this case, the connected component is ConnectedForm which requires a property called insertError. To fix this, your mapStateToProps should look like this:

const mapStateToProps = (state: IStore) => ({
    insertError: state.errors.insertError
})

A couple of important things to note about the above code:

  1. Make sure to include brackets around the curly braces in order for the TypeScript compiler to recognize that you are returning an object literal.
  2. Removing the explicit declaration of the return type as any allows the compiler to infer types correctly. Avoid specifying a return type and let the compiler handle it based on context.

For more information on implementing container components, check out this resource. Additionally, there are some TypeScript-specific tips available here.

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

Warning: ComponentMounts has been renamed. Proceed with caution

I'm encountering a persistent warning in my application and I'm struggling to resolve it. Despite running npx react-codemod rename-unsafe-lifecycles as suggested, the error persists and troubleshooting is proving to be challenging. The specific w ...

What is the best method for establishing a page location during rendering/onload?

It seems like there is a JavaScript event happening here using the onload attribute. But for the life of me, I can't seem to crack this code. <body onload="moveToHere('reference')"> I'm stuck and could really use some assistance ...

What is the process for transitioning global reusable types to package types within turborepo?

When creating an app within the apps folder, a global.d.ts file is required with specific types defined like this: interface Window{ analytics: any; } This file should be designed to be reusable and placed in the packages/types directory for easy acce ...

leveraging the tsconfig path for the source directory in the Next.js Image component

I'm attempting to store the path of my assets folder in the tsconfig file and then use it in the src attribute of the Image component, but for some reason it's unable to locate the address! This is what's in my tsconfig.js file: "paths ...

Node JS encountered an error: ECONNRESET was read at TCP.onStreamRead on line 211, column 20 in the node internal stream base commons

I am facing an issue while trying to insert a large array of data into my MySQL database using node.js. Everything works fine when dealing with smaller arrays, around 300 elements, but as soon as I try to insert an array with 1 million elements, I encounte ...

Guide on building a multi-page application using Vue or React

I find myself a bit confused when it comes to single-page applications versus multi-page applications. While I am aware of the difference between the two, I am struggling with creating a MPA specifically. Up until now, I have built various apps using Rea ...

The sorting icon cannot be substituted with jQuery, AJAX, or PHP

Currently, I am working on implementing "sort tables" using ajax, jquery, and PHP. The sorting function is functioning correctly; however, I need to show/hide the "sorting images". At the moment, only one-sided (descending) sorting is operational because I ...

Setting up angular-cli project for rc5- Step by step guide

Trying to integrate angular-cli with angular 2 rc5 but facing challenges: The issue of 'Promise' not being found After attempting to install 'npm install -g angular-cli@webpack', typings did not get installed, resulting in WebStorm un ...

Calculate the number of parent nodes and their respective child nodes

I am curious about how I can determine the number of children nested within parent-child relationships. For example: const parent = document.querySelectorAll('.parent'); parent.forEach(el => { const ul = el.querySelector('.child3-chi ...

What is the functionality of "classnames" in cases where there are multiple classes sharing the same name?

Currently, I am reviewing some code that utilizes the npm utility classnames found at https://www.npmjs.com/package/classnames. Within the scss file, there are various classes with identical names (small and large), as shown below: .buttonA { &.smal ...

Save the output of my Java function into a JavaScript variable

I have created a web application using JSP, CSS and HTML. The page contains six buttons, each of which calls a JavaScript method. For instance, the first button triggers the par() method. <html> <head> <title>Welcome d To Student Unive ...

Why is it that my WebMethod consistently produces JSON responses?

Excuse me if this question is a bit basic, as it's not my usual expertise. I have a WebMethod that returns a String (string table=""). However, the Ajax return function always interprets it as a JSON Object like {"d":{...}}. My question is WHY am I ...

Vue: Variable referenced in render without being declared

I'm running into an issue when trying to load my website. https://i.sstatic.net/4a2GS.png This is the code I am working with: <div v-if="bookings"> <div class="row"> < ...

Defining various scopes in Angular-Rails through user-defined input

Depending on user input, I have a range of 1 to 5 lists with arrays of items in each. The lists are named list1, list2... When I declare $scope using $scope.list = [], it doesn't specify which list it is referring to. While I could statically declare ...

Is there a way to incorporate the 'window' into middleware when using Express?

I am using middleware to retrieve data from a cookie with the help of vue-cookies. try { if (window.$cookies.get('region')) { res.setHeader('Set-Cookie', [ `region=${window.$cookies.get('region')};pat ...

Add an event listener to a dynamically created div block through jQuery when it is clicked

When the page loads, a dynamic div appears that is visible to the user and in Firebug, but is not available in the page source. The content within this div changes dynamically. I am attempting to bind a click event to this div so that when a user clicks o ...

A guide to eliminating duplicate values within an array and across multiple arrays with the help of jQuery

Looking for assistance with jQuery to find and alert repeated values in my code. Below are example arrays: a1 = {1,2,3,4,5,6,4} a2= {9,8,7}, a3= {a,b,c,d,e,7} I want to identify the value 4 in array "a1" and give an alert, as well as identify the value ...

Warning: Typescript is unable to locate the specified module, which may result

When it comes to importing an Icon, the following code is what I am currently using: import Icon from "!svg-react-loader?name=Icon!../images/svg/item-thumbnail.svg" When working in Visual Studio Code 1.25.1, a warning from tslint appears: [ts] Cannot ...

The function executes without issue initially but then consistently encounters errors

I'm facing an issue with my function running only once as expected. The JSON data for GhStatus and CsStatus is 0, so I anticipate receiving two "crash" alerts. However, the alerts are only triggered once. In Chrome Developer tools, I receive errors e ...

Troubleshooting resizing images in React using Material UI's useStyles

When attempting to resize an image using React, I am encountering a problem where adjusting the height and width of the tag with useStyles does not reduce the size of the image but instead moves it around on the page. Here is the code snippet: import { ma ...