Skip to content

Instantly share code, notes, and snippets.

@andreystarkov
Last active October 30, 2019 16: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 andreystarkov/1f402c616c3b73f814263529d4b824a4 to your computer and use it in GitHub Desktop.
Save andreystarkov/1f402c616c3b73f814263529d4b824a4 to your computer and use it in GitHub Desktop.
API Call Saga Example Usage
import { call, put, select } from 'redux-saga/effects'
import camel from 'to-camel-case'
export function * callAPI (api, action) {
let method = action.type.split('_')
method.pop()
method = camel(method.join('_'))
const apiCall = api[method]
const payload = { ...action }
delete payload.type
const state = yield select()
const { token } = state.Auth
if (token !== null) api.setToken(token.token)
const response = yield call(apiCall, { ...payload })
if (response.ok) {
const newType = action.type.replace('_REQUEST', '_SUCCESS')
const { data, headers } = response
const token = headers['access-token']
yield put({type: 'SET_TOKEN', token})
// вместо этого говна должно быть что-то универсальное
if (action.type === 'GET_RECOMMENDED_CITIES_REQUEST') {
yield put({ type: newType, data, index: action.index })
} else if (action.type === 'GET_MAP_OF_PRICES_REQUEST') {
yield put({ type: newType, data, direction: 'MAP_OF_PRICES' })
} else if (action.type === 'GET_CALENDAR_OF_PRICES_FOR_MONTH_REQUEST') {
yield put({ type: newType, data, direction: 'CALENDAR_OF_PRICES' })
} else {
yield put({ type: newType, data })
}
// localStorage.setItem('access-token', token)
} else {
const newType = action.type.replace('_REQUEST', '_FAILURE')
yield put({
type: newType,
problem: response.problem,
status: response.status,
errors: response.data.errors
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment