Skip to content

Instantly share code, notes, and snippets.

@m1el
Created January 27, 2019 04:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m1el/e9c41239f403255e5d8eae71ec3cdefc to your computer and use it in GitHub Desktop.
Save m1el/e9c41239f403255e5d8eae71ec3cdefc to your computer and use it in GitHub Desktop.
trying out redux
import * as React from 'react';
import * as ReactDOM from 'react-dom';
const getThings = (): Promise<Array<string>> => new Promise((resolve) => {
setTimeout(() => resolve(['a', 'b', 'c']), 500);
});
interface AppState {
loading: boolean;
things: Array<string>;
}
class App extends React.Component<{}, AppState> {
constructor(props: {}) {
super(props);
this.state = {
loading: false,
things: [],
};
}
componentDidMount() {
getThings().then(
(things) => this.setState({loading: false, things}));
this.setState({loading: true});
}
render() {
const { loading, things } = this.state;
return (
<div>
Hello World!
loading: {String(loading)},
things: {things.join(', ')}
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root') as HTMLElement
);
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { connect, Provider } from 'react-redux';
import { applyMiddleware, createStore, compose, Dispatch } from 'redux';
import thunk from 'redux-thunk';
const getThings = (): Promise<Array<string>> => new Promise((resolve) => {
setTimeout(() => resolve(['a', 'b', 'c']), 500);
});
// actions.ts
interface ActionLoad {
type: 'loading';
}
interface ActionLoaded {
type: 'loaded';
things: Array<string>;
}
type Action = ActionLoad | ActionLoaded;
const loadThings = () => {
return (dispatch: Dispatch<Action>) => {
dispatch({ type: 'loading' });
getThings().then((things) => {
dispatch({ type: 'loaded', things });
});
};
}
// reducer.ts
interface AppState {
loading: boolean;
things: Array<string>;
}
const defaultState: AppState = {
loading: false,
things: [],
};
const appReducer = (state: AppState = defaultState, action: Action) => {
if (action.type === 'loading') {
return {...state, loading: true};
}
if (action.type === 'loaded') {
return {...state, loading: false, things: action.things};
}
return state;
};
// store.ts
const store = createStore(
appReducer,
applyMiddleware(thunk)
);
// app.tsx
interface AppDispatch {
loadThings: () => void;
}
class PureApp extends React.Component<AppState & AppDispatch, {}> {
componentDidMount() {
this.props.loadThings();
}
render() {
const { loading, things } = this.props;
return (
<div>
Hello World!
loading: {String(loading)},
things: {things.join(', ')}
</div>
);
}
}
const App = connect<AppState, AppDispatch>(
(x: AppState) => x,
{loadThings}
)(PureApp);
// index.tsx
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root') as HTMLElement
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment