Skip to content

azmenak/use-saga-reducer

Repository files navigation

use-saga-reducer

npm codecov Build Status NPM

Use sagas without redux! This library provides an abstraction over Redux Saga's External API.

Install

npm install use-saga-reducer

Usage

import useSagaReducer from 'use-saga-reducer'
import {takeLatest, call, put} from 'redux-saga/effects'

function* dataFetcher() {
  try {
    const data = yield call(API.fetchData)
    yield put({type: 'FETCH_SUCCESS', payload: data})
  } catch (error) {
    yield put({type: 'FETCH_ERROR'})
  }
}

function* dataFetchingSaga() {
  yield takeLatest('FETCH', dataFetcher)
}

function reducer(state = {}, action) {
  if (action.type === 'FETCH_SUCCESS') {
    return action.payload
  }

  return state
}

const DataFetchingComponent: React.FC = () => {
  const [state, dispatch] = useSagaReducer(dataFetchingSaga, reducer)

  return (
    <>
      <pre>{state}</pre>
      <button onClick={() => dispatch({type: 'FETCH'})}>Fetch Data</button>
    </>
  )
}