Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a redux saga for API requests make sense?

I wonder if a generic request saga makes any sense?

It would take a REQUEST action that contains all the infos like headers, url, data and would merge it with its own headers and base URL. It would then fetch the request and then put(REQUEST_SUCCEEDED, json) with the json payload in the store.

const request = yield take(REQUEST)
const { url, data, headers } = request
try {
  if (request.startAction) {
    yield put(request.startAction)
  }
  const json = yield call(api.fetch, url, data, headers)
  yield put({...request.successAction, json})
} catch (error) {
  yield put({...request.errorAction, error})
}

As I understand it this would only allow one request at a time, so instead of calling the API fetch function a fork would be better?

The saga could also take care of managing the API access_token once it encounters it in the response headers and save it for all subsequent requests.

function getAction(action) {
  if (action) {
    if (typeof action === "string") {
      return { type: action }
    } else {
      return action
    }
  }
}

export function request(url, data, headers, actions) {
  let result = { 
    type: REQUEST,
    url, data, headers
  }
  actions[0] && result.startAction = getAction(actions[0])
  actions[1] && result.successAction = getAction(actions[1])
  actions[2] && result.errorAction = getAction(actions[2])
  return result
}
like image 571
philk Avatar asked Mar 02 '16 11:03

philk


1 Answers

There are several questions asked here.

  • Yes. Generic request saga makes sense to me. A place to provide standard for all requests makes sense.

  • Fork is most definitely needed. Or rather use takeEvery helper. This is to prevent missing some request while the saga is processing fetch. A default timeout may be needed to be implemented as well using race.

  • The actions parameter in request function would be better to be object than array with keys of startAction. An alternative is to give request a name. And make generic suffix for each action (eg. GETSTH_START, GETSTH_SUCCESS, GETSTH_ERROR)

like image 172
yjcxy12 Avatar answered Sep 20 '22 03:09

yjcxy12