Skip to content
This repository has been archived by the owner on Sep 10, 2022. It is now read-only.

withState that has same API as React state #321

Closed
timkindberg opened this issue Feb 24, 2017 · 2 comments
Closed

withState that has same API as React state #321

timkindberg opened this issue Feb 24, 2017 · 2 comments

Comments

@timkindberg
Copy link
Contributor

I found myself trying to use withState to recreate my own HOC that has the same state & setState API that a normal React class component has. The behavior (as we all probably know) is where setState() merges passed objects with existing state. The API is perfectly suited for managing local state.

I then wondered would it be more generally useful and also immediately familiar if withState mimicked the React state api?

Example:

const initialState = { foo: true };
const enhance = withState(initialState); // only 1 param needed
const Example = enhance(({ state, setState }) => // always 'state' and 'setState'
  <div>
    <button onClick={ () => setState({ bar: true }) } />
    <div>{ state.foo } and { state.bar }</div>
  </div>
);

Notice how I arbitrarily added bar. This version is very flexible.

I do like the current withState, but Recompose is the building blocks for custom HOCs. The current withState would be more easily composed using the withState above other than vice versa. Like so:

const legacyWithState = (name, method, initial) => compose(
  withState({ val: initial }),
  mapProps(({ state, setState }) => ({
    [name]: state.val,
    [method]: (val) => setState({ val })
  }))
);

Thoughts?

@istarkov
Copy link
Contributor

See #308,
we are also think about how to achieve the similar thing, trying also to auto memoize the method handler.

@wuct
Copy link
Contributor

wuct commented Feb 28, 2017

This thread can be discussed under #308, so I'm going to close this thread.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants