Skip to content

Instantly share code, notes, and snippets.

@njradford
Last active June 6, 2019 00:19
Show Gist options
  • Save njradford/104f1ff669094c1840c4b796e3027b92 to your computer and use it in GitHub Desktop.
Save njradford/104f1ff669094c1840c4b796e3027b92 to your computer and use it in GitHub Desktop.
import {getType} from 'typesafe-actions';
import {getSomething} from '@api';
import {fetchSomething} from '@actions';
import {AppState} from '@types';
async function handleFetchSomething({dispatch, getState, action, nextDispatchAsync}) {
const state: AppState = getState();
const params = buildParams(action.payload,state);
try {
const response = await getSomething(params);
dispatch(fetchSomething.success(response.data))
} catch (e) {
dispatch(fetchSomethingfailure(e.toString()))
}
}
export default [
{action: getType(fetchSomething.request), effect: handleFetchSomething}
]
import React from 'react';
import {createAsyncAction, createStandardAction, getType} from 'typesafe-actions';
export interface FetchSomethingArguments {
// ...
}
export interface SomethingType {
// ...
}
export const appSetNavBarOpen = createStandardAction('APP_SET_NAV_BAR_OPEN')<boolean>();
export const appFetchSomething = createAsyncAction(
'APP_FETCH_SOMETHING_REQUEST',
'APP_FETCH_SOMETHING_SUCCESS',
'APP_FETCH_SOMETHING_FAILURE'
)<FetchSomethingArguments, SomethingType, Error>();
export interface AppState {
navBarOpen: boolean
}
const DefaultAppState = {
navBarOpen: false
};
const appReducer = (state: AppState = DefaultAppState, action: any) => {
switch (action.type) {
case getType(appSetNavBarOpen):
// action.payload gets narrows to the FetchSomethingArguments type
return {
...state,
tocOpen: action.payload
};
case getType(appFetchSomething.request):
return {
// Request State
};
case getType(appFetchSomething.success):
return {
// Success State
};
case getType(appFetchSomething.failure):
return {
// Failure State
};
}
};
const SomeComponent = () => {
const getSomethingParams = {};
return <button onClick={() => appFetchSomething.request(getSomethingParams)}/>
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment