Redux saga & redux toolkit?

Answer

If you're interested in creating sagas that can resolve/reject async thunk actions then have a look at the saga-toolkit package - I created and use.

slice.js

import { createSlice } from '@reduxjs/toolkit'
import { createSagaAction } from 'saga-toolkit'

const name = 'example'

const initialState = {
result: null,
loading: false,
error: null,
}

export const fetchThings = createSagaAction(`${name}/fetchThings`)
export const doSomeMoreAsyncStuff = createSagaAction(`${name}/doSomeMoreAsyncStuff`)
const slice = createSlice({
name,
initialState,
extraReducers: {
[fetchThings.pending]: () => ({
loading: true,
}),
[fetchThings.fulfilled]: ({ payload }) => ({
result: payload,
loading: false,
}),
[fetchThings.rejected]: ({ error }) => ({
error,
loading: false,
}),
},
})

export default slice.reducer

sagas.js:-

import { call } from 'redux-saga/effects'
import { takeLatestAsync, takeEveryAsync, putAsync } from 'saga-toolkit'
import API from 'hyper-super-api'
import * as actions from './slice'

function* fetchThings() {
const result = yield call(() => API.get('/things'))

const anotherResult = yield putAsync(actions.doSomeMoreAsyncStuff()) // waits for doSomeMoreAsyncStuff to finish !

return result
}

function* doSomeMoreAsyncStuff() {
...
return 'a value for another result'
}

export default [
takeLatestAsync(actions.fetchThings.pending, fetchThings), // takeLatestAsync: behaves a bit like debounce
takeEveryAsync(actions.doSomeMoreAsyncStuff.pending, doSomeMoreAsyncStuff), // each action will start a new saga thread
]

 

All react js Questions

Ask your interview questions on react-js

Write Your comment or Questions if you want the answers on react-js from react-js Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---