Search code examples
reactjsreduxredux-saga

how to pass urls, params, headers to call() in redux-saga?


Theory regarding working of call() is well explained on many websites. However, I did not found any site which explains accurately with proper working example.

I have written following code:

export function* loadUser() {
    try {
    const user = yield call(getUser);
    yield put({type: 'FETCH_USER_SUCCESS', payload: user});

  } catch(error) {
    yield put({type: 'FETCH_FAILED', error});
  }
}    

here, I want to send 'get' request with some parameters and some header using call() .But I don't know how to achieve it. Please, if you have time, tell it with proper working example(Codepen or jsFiddle).


Solution

  • If you read the Redux Saga documentation you can see call takes a function and a spread array of arguments (comma separated):

    call(fn, ...args)

    You can use it like so:

    const getUsers = (options) => {
      return axios(options)
    }
    
    function *fetchUsers() {
      const users = yield call(getUsers, { method: 'get', url: `https://api.github.com/users` }, {user: 'my_username'})
      console.log(users)
    }
    

    Pretty straight forward.