DEV Community

mizchi (Kotaro Chikuba)
mizchi (Kotaro Chikuba)

Posted on

9 3

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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay