如何使用redux-saga添加书签

时间:2017-10-09 07:30:05

标签: javascript reactjs bookmarks redux-saga

这里的任何人都有一个带有redux-saga的书签应用程序示例?我使用过这个,但它只适用于redux-thunk - > https://github.com/KeerthiHarish/Bookmarks-Web-UI

1 个答案:

答案 0 :(得分:0)

您的/actions/index.js文件:

export function fetchBookmarks() {
    return { type: "FETCHING_BOOKMARKS" }
}

export function fetchBookmarksFulfilled(payload) {
    return { type: "FETCH_BOOKMARKS_FULFILLED", payload }
}

export function fetchBookmarksRejected(payload) {
    return { type: "FETCH_BOOKMARKS_REJECTED", payload }
}

export function createBookmark() {
    return { type: "CREATING_BOOKMARKS" }
}

export function createBookmarkFulfilled(payload) {
    return { type: "CREATE_BOOKMARKS_FULFILLED", payload }
}

export function createBookmarkRejected(payload) {
    return { type: "CREATE_BOOKMARKS_REJECTED", payload }
}

export function deleteBookmark() {
    return { type: "DELETING_BOOKMARKS" }
}

export function deleteBookmarkFulfilled(payload) {
    return { type: "DELETE_BOOKMARKS_FULFILLED", payload }
}

export function deleteBookmarkRejected(payload) {
    return { type: "DELETE_BOOKMARKS_REJECTED", payload }
}

export function associateBookmark() {
    return { type: "ASSOCIATING_BOOKMARK_FOLDER" }
}

export function associateBookmarkFulfilled(payload) {
    return { type: "ASSOCIATE_BOOKMARK_FOLDER_FULFILLED", payload }
}

export function associateBookmarkRejected(payload) {
    return { type: "ASSOCIATE_BOOKMARK_FOLDER_REJECTED", payload }
}

你的/sagas/index.js文件:

import axios from 'axios';
import { all, call, put, take } from 'redux-saga/effects';
import {
    fetchBookmarksFulfilled,
    fetchBookmarksRejected,
    // the rest actions
}

export default function* rootSaga() {
    yield all([
        call(fetchBookmarksSaga),
        call(createBookmarksSaga),
        call(deleteBookmarksSaga),
        call(associateBookmarksSaga),
    ])
}

function* fetchBookmarksSaga() {
    while (true) {
        try {
            yield take("FETCHING_BOOKMARKS")
            const response = yield call(axios.get, "https://bookmarks-rest-api.herokuapp.com/bookmarks")
            yield put(fetchBookmarksFulfilled(response.data))
        } catch (error) {
            yield put(fetchBookmarksRejected(error))
        }
    }
}

// likewise create, delete and associate sagas

在您的App.js中:

import createSagaMiddleware from 'redux-saga'
import rootSaga from './sagas'

sagaMiddleware = createSagaMiddleware()
store = createStore(reducers, persistedState, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga)