1.0.2 • Published 6 years ago

hypereact v1.0.2

Weekly downloads
2
License
MIT
Repository
github
Last release
6 years ago

hypereact

A lightweight React state management which inspired on hyperapp

Hypereact in action

  1. Todo App: https://codesandbox.io/s/23r32ynkxj

Samples

Declare store

import hypereact from "hypereact";
const initialState = {
  todos: {},
  ids: [],
  text: ""
};
hypereact(initialState);

Declare an action

Add.js

import hypereact from "hypereact";
import update from "immhelper";
import uuid from "uuid";

export const dispatch = text => state => {
  // generate random id
  const id = uuid();

  return update(state, {
    // update todo map
    todos: ["set", id, { done: false, text }],
    // update id list
    ids: ["push", id],
    // clear input text
    text: ""
  });
};

export default hypereact({
  dispatch
});

Declare a view

TodoForm.js

import React from "react";
import hypereact from "hypereact";
import Add from "./Add";
import ChangeText from "./ChangeText";

export const render = ({ text, add, changeText }) => (
  <form
    onSubmit={e => {
      e.preventDefault();
      add(text);
    }}
  >
    <input
      type="text"
      value={text}
      onChange={e => changeText(e.target.value)}
      placeholder="Enter new todo"
    />
  </form>
);

export default hypereact({
  // specified dependency actions
  actions: [Add, ChangeText],
  // map state to props
  state: ({ text }) => ({ text }),
  // map dispatch to props
  dispatch: (props, add, changeText) => ({
    add,
    changeText
  }),
  render
});

ChangeText.js

import hypereact from "hypereact";
import update from "immhelper";

export const dispatch = text => state => update(state, { text });

export default hypereact({
  dispatch
});

State change subscription

import { subscribe } from "hypereact";
const unsubscribe = subscribe(state => console.log(state));

unsubscribe();

Dispatch action from outside view

import { dispatch } from "hypereact";
import Action from "./Action";

dispatch(Action, arg1, arg2, arg3);

Dispatch action from other action

// ActionA.js
import hypereact from "hypereact";
import ActionB from "./ActionB";
import ActionC from "./ActionC";

const dispatch = (arg1, arg2) => (state, actionB, actionC) => {
  actionB(arg1);
  actionC(arg2);
};

export default hypereact({
  actions: [ActionB, ActionC],
  dispatch
});