Skip to content

Instantly share code, notes, and snippets.

@wvengen wvengen/README.md
Last active Feb 8, 2019

Embed
What would you like to do?
Basic redux-api example
<!DOCTYPE html>
<html>
<head>
<title>Basic redux-api sample</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.5.2/redux.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux-thunk/2.1.0/redux-thunk.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/4.4.5/react-redux.js"></script>
<script src="https://cdn.rawgit.com/lexich/redux-api/0.9.8/dist/redux-api.js"></script>
</head>
<body>
<div id="app"></div>
<script src="index.js" type="text/babel"></script>
</body>
</html>
// redux-api
const ReduxApi = window['redux-api'];
const rest = ReduxApi({
status: 'status-:kind.json'
}).use('fetch', (url, opts) => fetch(url, opts).then(r => r.json()));
// Redux store
const createStoreWithMiddleware = Redux.applyMiddleware(ReduxThunk.default)(Redux.createStore);
const reducer = Redux.combineReducers(rest.reducers);
const store = createStoreWithMiddleware(reducer);
// Status container
const Status = ({status}) => (
<div style={{fontSize: '180%', margin: '3ex'}}>
Status is <em>{(status.data && status.data.status) || 'unknown'}</em>
{status.syncing ? <span style={{color: 'blue'}}> (busy)</span> : null}
{status.error ? <span style={{color: 'red'}}> (error)</span> : null}
</div>
);
Status.propTypes = {
status: React.PropTypes.object.isRequired,
};
const StatusContainer = ReactRedux.connect(state => ({status: state.status}))(Status);
// Main app
class App extends React.Component {
render() {
return (
<div>
<h1>Basic <a href="https://github.com/lexich/redux-api">redux-api</a> example</h1>
<StatusContainer />
<div>
<button onClick={() => this._onClick('ok')}>update (success)</button>
<button onClick={() => this._onClick('xx')}>update (failure)</button>
</div>
</div>
);
}
_onClick(kind) {
this.props.dispatch(rest.actions.status.reset('sync'));
this.props.dispatch(rest.actions.status.sync({kind}));
}
}
App.propTypes = {
dispatch: React.PropTypes.func.isRequired,
};
const AppContainer = ReactRedux.connect()(App);
// Setup app
ReactDOM.render(
<ReactRedux.Provider store={store}>
<AppContainer />
</ReactRedux.Provider>,
document.getElementById('app'));
{
"status": "ok"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.