Last active
October 30, 2019 16:24
-
-
Save andreystarkov/1f402c616c3b73f814263529d4b824a4 to your computer and use it in GitHub Desktop.
API Call Saga Example Usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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