sc0ttj / component

A tiny library for isomorphic JavaScript components
MIT License
2 stars 1 forks source link

Feature: `fromState` module #32

Closed sc0ttj closed 3 years ago

sc0ttj commented 3 years ago

fromState

Aside from adding more React-like modules (useState, useEffect, etc) I'd also like something even simpler than useState - a fromState method that simply works like so:

// a stateful component using "fromState()"

function Foo(props) {
  const { title, count } = fromState();
  return `<div>...</div>`;
}

// ...or a stateful component using initial state: "fromState([ ...initial values ])"

function Foo(props) {
  const { title, count } = fromState([ "initial text", 0 ]);
  return `<div>...</div>`;
}

At a minimum, fromState() would basically do this:


// return initial state, or latest state (with props any merged in)
const fromState = (initial) => {
  this.state = { ...initial, ...this.state, ...props };
  return this.state;
}

..as far as I understand it, the above pattern should work because:

  1. the props received by the component will be known to fromState without having to pass it in
  2. this keyword in the fromState function will refer to the component in which it's called, as long as:
    • fromState is an arrow function

...I need to test that theory...

Modified use-st8

Another option may be to extend use-st8 so that the functions it returns have a custom .toString() method, which return the state property value that the func is responsible for.

That way, you could update the state as in use-st8, but also use them as ordinary variables in your HTML templates... like so:

const Foo(props){
  const { count, msg } = fromState([ 0, "Loading" ]);
  // update the state values
  count(v => v + 1)
  msg(v => v + "..")
 // use them in your templates like they're normal variables
 return `<div>${count}: ${msg}div>`
}

using Observables

...even better... also use observables to create a much nicer, cleaner syntax:

// update the state values *using observables*:
//     fromState() listens to any changes to the props its gives
//     back, and updates them in `this.state` for you whenever 
//     you update them in your component:

const Foo(props){
  const { count, msg } = fromState([ 0, "Loading" ]);
 return `<div>${count += 1}: ${msg += ".."}</div>`
}
sc0ttj commented 3 years ago

also see this for ideas: https://github.com/fabiospampinato/store/blob/master/resources/demo.png

sc0ttj commented 3 years ago

Not needed, very low priority.. Closing.

sc0ttj commented 2 years ago

Very small, easy to use Observable library: https://github.com/jbreckmckye/trkl