sc0ttj / component

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

Feature: allow passing functions to setState() #26

Closed sc0ttj closed 3 years ago

sc0ttj commented 3 years ago

Instead of only passing objects to setState, make it possible to pass functions too:

myComponent.setState(currentState => {
  const newState = await doStuff(currentState);
  return newState;
});

This function will be called by Component and the current version of the state will be passed as an argument. This way is called a “functional update.”

This might be useful whenever you need multiple asynchronous functions (doStuff) to share a state.


More flexible middleware:

setState cannot receive an callback as a 2nd param, cos schema is the 2nd param...

So cant do this:

// call set state, and pass in an array of functions to run
// immediately after state is updated, and before render() 
// is called
Foo.setState({ ... someData }, [ fn1, fn2 ]);

But could do this instead:

If middleware is an object, user can choose when to run the middleware:

Foo.actions({
  addOne: props => props + 1
})

Foo.middlware = {
  initial:  [ fn1, fn2 ],
  preSetState: [ fn1, fn2 ],
  preRender:   [ fn3, fn4 ],
  postRender: [ fn5, fn6 ],
  // for every action
  preAction: [...],
  postAction: [...],
  // for specific "actions" 
  preAddOne: [...],
  postAddOne: [...],
}

...or something similar..

sc0ttj commented 3 years ago

Overthinking .. Just use async stuff with "actions".. And run stuff in your "actions" then setState to do the middle ware stuff..