Chaim Friedman
Chaim Friedman

Reputation: 6253

how to type react-redux connect in flow?

This is what my mapStateToProps looks like.

const mapStateToProps = (state): StateProps => {
    let status = false;
    if (state.productsPage.currentProduct) {
        if (state.productsPage.currentProduct.status === "ACTIVE") {
            status = true;
        }
    }
    return {
        showModal: state.productsPage.showModal,
        currentProduct: state.productsPage.currentProduct,
        isLoading: state.status.loading.PRODUCTS_EDIT,
        initialValues: {
            name: state.productsPage.currentProduct ? state.productsPage.currentProduct.name : "",
            status,
        },
    };
};

Here is the shape of StateProps

type StateProps = {
    showModal: boolean,
    currentProduct: Object,
    isLoading: boolean,
    initialValues: {
        name: string,
        status: boolean,
    }
}

This is my usage of connect.

const connected = connect<React$StatelessFunctionalComponent<any>, StateProps>(mapStateToProps, mapDispatchToProps);

This produces the following error, and I have no idea what it means or how to go about solving it.

[flow] Cannot call connect because property currentProduct is missing in React.StatelessFunctionalComponent [1] in the indexer property's key of type argument ST. (References: [1])

Upvotes: 5

Views: 2775

Answers (2)

wgao19
wgao19

Reputation: 523

It is recommended that you upgrade Flow to at least past 0.89, and use Flow Typed's newest React Redux library definition.

Then, you can annotate the connected components with Props and OwnProps

import * as React from 'react'

type OwnProps = {|
  passthrough: string,
  forMapStateToProps: string
|}

type Props = {|
  ...OwnProps,
  fromMapStateToProps: string,
  dispatch1: () => void
|}

const MyComponent = (props: Props) => (
  <div onClick={props.dispatch1}>
    {props.passthrough}
    {props.fromMapStateToProps}
  </div>
)

export default connect<Props, OwnProps, _, _, _, _>(
  mapStateToProps,
  mapDispatchToProps
)(MyComponent)

Here is a more detailed guide that includes a couple more use cases.

Upvotes: 3

Charles Stover
Charles Stover

Reputation: 1148

React$StatelessFunctionalComponent is a generic that expects prop types. Instead of <any>, you would want the props that that function expects to receive -- most importantly, it expects to receive your StateProps returned by mapStateToProps (though it may expect others in addition).

It may change depending on version of react-redux, but I am seeing some documentation that suggests that the generics for connect are the return value of mapStateToProps, not a React element. - Source

You may be needing connect<StateProps, DispatchPropsIfAny> instead of providing an Element type.

Upvotes: 0

Related Questions