Skip to content

Instantly share code, notes, and snippets.

@broerjuang
Last active September 13, 2018 19:23
Show Gist options
  • Save broerjuang/5d07c04765921f7890dc291afd150922 to your computer and use it in GitHub Desktop.
Save broerjuang/5d07c04765921f7890dc291afd150922 to your computer and use it in GitHub Desktop.
Redux Context
async function getUsersAsync(dispatch) {
dispatch({ type: "FETCH_REQUESTED" });
try {
let data = await fetch("https://api.github.com/users").then(res =>
res.json()
);
dispatch({ type: "FETCH_SUCCEED", data });
} catch (error) {
dispatch({ type: "FETCH_FAILED", error: error });
}
}
export default getUserAsync;
import React, { Component } from "react";
import { StoreProvider as Provider, Consumer } from "./StoreProvider";
import getData from "./counter/asyncAction";
import rootReducer from "./rootReducer";
class App extends Component {
render() {
return (
<Provider rootReducer={rootReducer}>
<Consumer>
{({ state, dispatch }) => {
return (
<h1 onClick={() => getData(dispatch)}>
state: {JSON.stringify(state.user)}
</h1>
);
}}
</Consumer>
</Provider>
);
}
}
export default App;
import * as React from "react";
import autobind from "class-autobind";
let { Provider, Consumer } = React.createContext({});
class StoreProvider extends React.Component {
constructor() {
super(...arguments);
autobind(this);
this.state = {
state: this.props.rootReducer(undefined, "@@INIT"),
dispatch: this._dispatch
};
}
render() {
return <Provider value={this.state}>{this.props.children}</Provider>;
}
_dispatch(action) {
this.setState(prevState => {
return {
...prevState,
state: this.props.rootReducer(this.state.state, action)
};
});
}
}
export { StoreProvider, Consumer };
import { combineReducers } from "redux";
function userReducer(
state = { data: null, isLoading: false, error: null },
action
) {
switch (action.type) {
case "FETCH_USERS_REQUESTED": {
return {
isLoading: true,
data: null,
error: null
};
}
case "FETCH_USERS_FAILED": {
return {
isLoading: false,
error: action.error,
data: null
};
}
case "FETCH_USERS_SUCCEED": {
return {
isLoading: false,
error: null,
data: action.data
};
}
default: {
return state;
}
}
}
function counterReducer(state = 0, action) {
switch (action.type) {
case "INCREMENT": {
return state + 1;
}
case "DECREMENT": {
return state - 1;
}
case "RESTART": {
return 0;
}
default: {
return state;
}
}
}
let rootReducer = combineReducers({ counter, user });
export default rootReducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment