DEV Community

Cover image for About redux-saga/effects put, call, take, select
off.tokyo
off.tokyo

Posted on

About redux-saga/effects put, call, take, select

This time I used call, fork, put, take, and select.

  • call: Wait for the promise to finish. The argument should be a function that returns a promise.
  • fork: Start another task. The argument can be an asynchronous function starting with *function*.
  • put: Dispatch an action.
  • take: wait for an action, an event to occur, and take as argument a string that is not a function of the action, but an action.type.
  • select: select data from a state, taking a function that takes a state as an argument.

When importing, use

 


import { call, fork, put, take, select } from 'redux-saga/effects'.

Write something like

 

Here is a sample code

 



function* callSample(){
    const { result, err } = yield call(getData) 
    if(result){
        console.log(result)
    } else {
        console.error(err)
    }
}

const getData = () => {
    return axios.get('./get')
        .then( res => {
            const result = res
            return {result} 
        })
        .catch( err => {
            return {err}
        })
}

If you give an argument to a function that returns a promise in call, it looks like this

 


function* callSample2(){
    const data = {
      name: 'hoge',
      password:'huga'
    }
    const {responce, err} = yield call(postData(data))
}
const postData = (data) => {
    return axios('./post')
        .then( () => { /*something*/ }
        .catch( () => { /*something*/ }
}

 

The fork is a branch of the root task, and the process is written.

 


//fork sample
export default function* rootSaga(){
    yield fork(forkSample)
}
function* forkSample(){
   //processing
}

 

Put is used to dispatch actions according to the results of other asynchronous processes.

 


//put sample
function* putSample(){
    const { result, err } = yield call(getData) 
    if(result){
        yield put(get(result))
    } else {
        console.log(err)
    }
}

 

Take will be executed when dispatched from elsewhere.

 



function* takeSample(){
    while(true) {
        const action = yield take("ADD")
    }
}

 



function* selectSample() {
        const state = yield select(getState)
    }
}


const getState = (state) => ( state )

 

Top comments (0)