DEV Community

Koutaro Chikuba
Koutaro Chikuba

Posted on

Static HOC analysis for recompose and redux by flowtype

flow@60.1

Need these definitons

/* @flow */
import React from 'react'
import { bindActionCreators, combineReducers } from 'redux'
import { compose, lifecycle, pure, type HOC } from 'recompose'
import { connect } from 'react-redux'

// reducer
const INC = 'inc'

const inc = () => ({ type: INC })

type Counter = {
  value: number
}

type Action = $Call<typeof inc>

const counter = (state: Counter = { value: 0 }, action: Action): Counter => {
  switch (action.type) {
    case INC: {
      return { value: state.value + 1 }
    }
    default: {
      return state
    }
  }
}

const rootReducer = combineReducers({ counter })

// Get RootState from result of rootReducer
type RootState = $Call<typeof rootReducer>

// compose HOCs

type OuterProps = {
  foo: string
}

type Props = {
  foo: string,
  bar: number,
  actions: {
    inc: Function
  }
}

const connector = connect(
  (state: RootState, props) => {
    return {
      foo: props.foo,
      bar: state.counter.value
    }
  },
  dispatch => bindActionCreators({ inc }, dispatch)
)

const enhancer: HOC<Props, OuterProps> = compose(
  connector,
  pure,
  lifecycle({
    componentDidMount() {
      console.log('mounted')
    }
  })
)

// props is resolved by hoc
const MyComponent = enhancer(props => {
  return (
    <div>
      {props.foo}
      {props.bar}
      {props.actions.inc}
    </div>
  )
})
Enter fullscreen mode Exit fullscreen mode

Check them on flowtype

You can check and complete codes on part of mapStateToProps and MyComponent's props.

Top comments (0)