Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Redux connect issues in typescript

I am a trying to make a component which gets passed to react-redux's connect function. The component is as follows:

interface ITestProps {
  id: number
}

class TestComponent extends React.Component<ITestProps, {}> {
  render() {
    return (<div>
      {this.props.name}
    </div>)
  }
}

mapStateToProps(state) {}
mapDispatchToProps(dispatch) {}

let ConnectedComponent = connect(
  mapStateToProps,
  mapDispatchToProps
)(TestComponent)

The above code seems to work find if i render ConnectedComponent like so

<ConnectedComponent></ConnectedComponent>

i.e without the id prop. Shouldn't it throw an error since the ConnectedComponent is simply the connected form of TestComponent and TestComponent should have props of the form ITestProps. Is this how it is supposed to behave or am I doing something wrong.

like image 203
Nahush Farkande Avatar asked Jul 07 '16 10:07

Nahush Farkande


People also ask

Does Redux work with TypeScript?

We strongly recommend using TypeScript in Redux applications. However, like all tools, TypeScript has tradeoffs. It adds complexity in terms of writing additional code, understanding TS syntax, and building the application.

Does React work well with TypeScript?

Better support for JSX Another additional benefit of TypeScript + React is that it provides better IntelliSense, code completion for JSX. Tip: Share your reusable components between projects using Bit (Github). Bit makes it simple to share, document, and reuse independent components between projects.

Should you combine hooks with Redux?

We recommend using the React-Redux hooks API as the default approach in your React components. The existing connect API still works and will continue to be supported, but the hooks API is simpler and works better with TypeScript. These hooks were first added in v7.1.0.


2 Answers

I'm not sure why the typings can't infer the type from the presentational component alone, but it will work if ownProps is typed in connect ->

let ConnectedComponent = connect<{}, {}, ITestProps>(
  mapStateToProps,
  mapDispatchToProps
)(TestComponent)

It also can infer it if ownProps is typed in mapDispatchToProps ->

mapStateToProps(state, ownProps: ITestProps) {}
like image 163
Radio- Avatar answered Oct 28 '22 00:10

Radio-


Include a constructor inside the class like this:

constructor(props) {
  super(props)
}

Without the constructor the props don't get loaded

Instead of

let ConnectedComponent = connect(
  mapStateToProps,
  mapDispatchToProps
)(TestComponent)

I added (obviously mapStateToProps & mapDispatchToProps have to be defined before the connect function)

@connect(mapStateToProps, mapDispatchToProps)

above

class TestComponent extends React.Component<ITestProps, {}> {
like image 35
suku Avatar answered Oct 28 '22 00:10

suku