0.0.0 • Published 12 months ago

expressive-mvc v0.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
12 months ago

Classes which extend Model can manage behavior for components. Models are easy to extend, use and even provide via context. While hooks are great, state and logic are not a part of well-formed JSX. Models help wrap that stuff in robust, typescript controllers instead.

Install with your preferred package manager

npm install --save @expressive/react

Import and use in your react apps

import Model from "@expressive/react";

Ultimately, the workflow is simple.

  1. Create a class. Fill it with the values, getters, and methods you'll need.
  2. Extend Model (or any derivative, for that matter), making it reactive.
  3. Within a component, use built-in methods as you would normal hooks.
  4. Destructure out the values used by a component, to then subscribe.
  5. Update those values on demand. Component will sync automagically. ✨

A basic example

Step 1

Create a class to extend Model and fill it with values of any kind.

import Model from "@expressive/react";

class Counter extends Model {
  current = 1

  increment = () => { this.current += 1 };
  decrement = () => { this.current -= 1 };
}

Step 2

Pick a built-in hook, such as use(), inside a component to make it stateful.

const KitchenCounter = () => {
  const { current, increment, decrement } = Counter.use();

  return (
    <div>
      <button onClick={decrement}>{"-"}</button>
      <pre>{current}</pre>
      <button onClick={increment}>{"+"}</button>
    </div>
  )
}

Step 3

See it in action 🚀 — You've already got something usable!

Expressive leverages the advantages of classes to make state management simpler. Model's fascilitate binding between components and the values held by a given instance. Here are some of the things which are possible.

Track any number, even nested values:

Models use property access to know what needs an update when something changes. This optimization prevents properties you do not "import" to cause a refresh. Plus, it makes clear what's being used!

class Info extends Model {
  info = new Extra();
  foo = 1;
  bar = 2;
  baz = 3;
}

class Extra extends Model {
  value1 = 1;
  value2 = 2;
}

const MyComponent = () => {
  const {
    foo,
    bar,
    info: {
      value1
    }
  } = Info.use();

  return (
    <ul>
      <li>Foo is {foo}</li>
      <li>Bar is {bar}</li>
      <li>Info 1 is {value1}</li>
    </ul>
  )
}

View in CodeSandbox

Here, MyComponent will subscribe to foo and bar from a new instance of Test. You'll note baz is not being used however - and so it's ignored.

Update using simple assignment:

State management is portable because values are held in an object. Updates may originate from anywhere with a reference to the model. Logic can live in the class too, having strict types and easy introspection.

class State extends Model {
  foo = 1;
  bar = 2;
  baz = 3;

  barPlusOne = () => {
    this.bar++;
  }
}

const MyComponent = () => {
  const { is: state, foo, bar, baz } = State.use();

  useEffect(() => {
    const ticker = setInterval(() => {
      state.baz += 1;
    }, 1000);

    return () => clearInterval(ticker);
  }, [])

  return (
    <ul>
      <li onClick={() => state.foo++}>
        Foo is {foo}!
      </li>
      <li onClick={state.barPlusOne}>
        Bar is {bar}!
      </li>
      <li>
        Bar is {baz}!
      </li>
    </ul>
  )
}

View in CodeSandbox

Reserved property is loops back to the instance, helpful to update values after having destructured.

Control components with async functions:

With no additional libraries, expressive makes it possible to do things like queries quickly and simply. Sometimes, less is more, and async functions are great for this.

class Greetings extends Model {
  response = undefined;
  waiting = false;
  error = false;

  sayHello = async () => {
    this.waiting = true;

    try {
      const res = await fetch("http://my.api/hello");
      this.response = await res.text();
    }
    catch(e) {
      this.error = true;
    }
  }
}

const MyComponent = () => {
  const { error, response, waiting, sayHello } = Greetings.use();

  if(response)
    return <p>Server said: {response}</p>

  if(error)
    return <p>There was an error saying hello.</p>

  if(waiting)
    return <p>Sent! Waiting on response...</p>

  return (
    <a onClick={sayHello}>Say hello to server!</a>
  )
}

View in CodeSandbox

Extend to configure:

Capture shared behavior as reusable classes and extend them as needed. This makes logic reusable and easy to document and share!

import { toQueryString } from "helpers";

abstract class Query extends Model {
  /** This is where you will get the data */
  url: string;

  /** Any query data you want to add. */
  query?: { [param: string]: string | number };

  response = undefined;
  waiting = false;
  error = false;

  sayHello = async () => {
    this.waiting = true;

    try {
      let { url, query } = this;

      if(query)
        url += toQueryString(query);

      const res = await fetch(url);
      this.response = await res.text();
    }
    catch(e) {
      this.error = true;
    }
  }
}

Now you can extend it in order to use!

class Greetings extends Query {
  url = "http://my.api/hello";
  params = {
    name: "John Doe"
  }
}

const Greetings = () => {
  const { error, response, waiting, sayHello } = Greetings.use();

  return <div />
}

Or you can just use it directly...

const Greetings = () => {
  const { error, response, waiting, sayHello } = Query.use({
    url: "http://my.api/hello",
    params: { name: "John Doe" }
  });

  return <div />
}

It works either way!

Share state between components using context:

Providing and consuming models is dead simple using Provider and get methods. Classes act as their own key!

import Model, { Provider } from "@expressive/react";

class State extends Model {
  foo = 1;
  bar = 2;
}

const Parent = () => {
  const state = State.use();

  // Instance `state` is now available as its own class `State`
  return (
    <Provider for={state}>
      <AboutFoo />
      <AboutBar />
    </Provider>
  )
}

const AboutFoo = () => {
  // Like with `use` we retain types and autocomplete!
  const { is: state, foo } = State.get();

  return (
    <p>
      Shared value foo is: {foo}!
      <button onClick={() => state.bar++}>
        Plus one to bar
      </button>
    </p>
  )
}

const AboutBar = () => {
  const { is: state, bar } = State.get();

  return (
    <p>
      Shared value bar is: {bar}!
      <button onClick={() => state.foo++}>
        Plus one to foo
      </button>
    </p>
  )
}

View in CodeSandbox

0.0.0

12 months ago