phpsmarter
1/16/2018 - 9:53 AM

List stateless with recompose

List stateless with recompose

import React from "react";
import { pure, withReducer, compose, withHandlers, mapProps } from "recompose";
import R from "ramda";
import { createReducer } from "./utils";

const ListItem = pure(({ text }) => <li>{text}</li>);
const renderItems = R.map(t => <ListItem key={t} text={t} />);

const ListComponent = ({ todos, name, updateName, addTodo }) =>
  <div>
    <input onChange={updateName} value={name} />
    <button onClick={() => addTodo(name)}>add todo</button>
    <ul>
      {renderItems(todos)}
    </ul>
  </div>;

const initialState = { todos: [], name: "" };
const listReducer = createReducer({
  UPDATE_NAME: (state, payload) => ({ name: payload }),
  ADD_TODO: (state, payload) => ({ todos: [...state.todos, payload] })
});

const List = compose(
  withReducer("state", "dispatch", listReducer, initialState),
  withHandlers({
    updateName: ({ dispatch }) => e =>
      dispatch({ type: "UPDATE_NAME", payload: e.target.value }),
    addTodo: ({ dispatch, name }) => name =>
      dispatch({ type: "ADD_TODO", payload: name })
  }),
  mapProps(({ state, ...props }) => ({ ...state, ...props }))
)(ListComponent);

export default List;