drcmda / react-contextual

🚀 react-contextual is a small (less than 1KB) helper around React 16s new context api
MIT License
642 stars 22 forks source link

Pull Request: simplify the API for create store #21

Closed songguoqiang closed 6 years ago

songguoqiang commented 6 years ago

I would like to propose the following API.

To use the built-in ProviderContext

const store = {
    count: 0,
    up: () => state => ({ count: state.count + 1 }),
    down: () => state => ({ count: state.count - 1 }),
}

const App = () => (
    <Provider {...store}>
        <Subscribe>
            {props => (
                <div>
                    <h1>{props.count}</h1>
                    <button onClick={props.up}>Up</button>
                    <button onClick={props.down}>Down</button>
                </div>
            )}
        </Subscribe>
    </Provider>
)

To use external store

const externalStore = createStore({
    text: 'Hello',
    setText: text => ({ text })
})

const App = () => (
    <Provider store={store}>
        <Subscribe to={store}>
            {props => <div>{props.text}</div>}
        </Subscribe>
    </Provider>
)

Compared with the current API, there are two changes: (1) we don't need to specify "initialState" and "action" anymore. (2) we don't support the global functions in the store anymore.

Each store contains just one javascript object, which has some states and the functions to update those states. In this way, the store concept is similar to the container concept in the unstated.

Note:

codecov-io commented 6 years ago

Codecov Report

Merging #21 into master will not change coverage. The diff coverage is 100%.

Impacted file tree graph

@@          Coverage Diff          @@
##           master    #21   +/-   ##
=====================================
  Coverage     100%   100%           
=====================================
  Files           6      6           
  Lines          85     86    +1     
=====================================
+ Hits           85     86    +1
Impacted Files Coverage Δ
src/store.js 100% <100%> (ø) :arrow_up:

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update 7b10dec...4777972. Read the comment docs.

drcmda commented 6 years ago

@songguoqiang looks good to me! Could you update readme and api as well? I'd later adapt the sandbox examples.

songguoqiang commented 6 years ago

@drcmda please have a check.

When I updated the API.md, I realized the API of the external store is a bit awkward, e.g. externalStore.getState().up(), which was externalStore.actions.up() previously.

That's because the up action now becomes part of the state field in the external store.

drcmda commented 6 years ago

@songguoqiang sorry for the long wait, i've been so busy with work atm, the gestState() part is fine with me, functions are now part of state.