0.2.3 • Published 7 years ago

redux-saga-rest v0.2.3

Weekly downloads
6
License
MIT
Repository
github
Last release
7 years ago

redux-saga-rest

npm version

redux-saga-rest is a thin wrapper around the Fetch API that integrates with redux-saga and supports request/response middleware.

Installation

# dependencies
yarn add redux redux-saga isomorphic-fetch

yarn add redux-saga-rest

Usage Example

api.js

import { put, select } from 'redux-saga/effects';
import { API } from 'redux-saga-rest';

import * as selectors from './selectors';
import * as actions from './actions';

const authMiddleware = () => function* (req, next) {

    // request middleware
    const user = yield select(selectors.user);
    const headers = req.headers || new Headers();
    headers.set('Authorization', `Bearer ${user.token}`);

    // retrieve the response
    const res = yield next(new Request(req, { headers }));

    // response middleware
    if (res.status === 401) {
        yield put(actions.logout());
    }

    // return the response
    return res;
};

export const auth = new API('/api/')
    .use(authMiddleware());

TODO: Describe the middleware application order.

sagas.js

import { takeEvery, put } from 'redux-saga/effects';

import * as constants from './constants';
import * as actions from './actions';
import { auth } from './api';

function* watchUpdateProfile() {
    yield takeEvery(constants.UPDATE_PROFILE, function* (action) {
        const res = yield auth.patch('/profile/', action.payload);
        
        if (res.ok) {
            yield put(actions.updateProfileSuccess());
        } else {
            yield put(actions.updateProfileFailure());
        }
    });
}

export default function* () {
    yield [
        watchUpdateProfile(),
    ];
};
0.2.3

7 years ago

0.2.2

7 years ago

0.2.1

7 years ago

0.2.0

7 years ago

0.1.8

7 years ago

0.1.7

7 years ago

0.1.6

7 years ago

0.1.5

7 years ago

0.1.4

7 years ago

0.1.3

7 years ago

0.1.2

7 years ago

0.1.1

8 years ago

0.1.0

8 years ago

0.0.2

8 years ago

0.0.1

8 years ago