add editor state vars with typescript an recompose

add editor state vars with typescript an recompose

If you need to add editor state to any class you can use recompose.

Here’s the basics:

/** What the output of [addEditorState] will receive as input. */
export interface EditorProps {
 isDirty:  boolean
 isEditing:  boolean
 setDirty: (v:  boolean) =>  void
 setEditing: (v:  boolean) =>  void
 resetDirty: () =>  void
 resetEditing: () =>  void
}

and the recompose part:

/**
* HOC to add isDirty and isEditing state management plus a few functions.
* Input component goes from from `P extends EditorProps` => `P omit EditorProps`.
*/

export  function  addEditorState<P  extends  EditorProps>(component:  React.ComponentType<P>) {
  return  compose<P, Omit<P, EditorProps>>(
   withState("isEditing", "setEditing", false),
   withState("isDirty", "setDirty", false),
   withHandlers({
     resetDirty: ({ setDirty }) => () =>  setDirty(false),
     resetEditing: ({ setEditing }) => () =>  setEditing(false)
    })
  )(component)
}

Note the use of Omit which is defined on the typescript site:

/**
* Omit right side from left side.
* @see  https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-311923766
* @see  https://github.com/pelotom/type-zoo
*/
export  type  Omit<T, K> =  Pick<T, Exclude<keyof  T, keyof  K>>

Now we can add the basic editor state to any element we need to. Notice that with typescript, we have removed EditorProps from the props type of the resulting component since those are arriving via recompose with the extra state and handles.

export interface BlahProps extends EditorProps {
...
} 
export class BlahEditor extends React.Component<BlahProps, State> {
 ...
}
export BlahEditorWithEditorState = addEditorState<BlahEditorProps>(BlahEditor)

Popular posts from this blog

React, Redux, Recompose and some simple steps to remove "some" boilerplate and improve reuse

cats/cats-effect and webservices function composition

graphql (facebook), falcor (netflix) and odata and ...