[Django]-Redux-Saga pass headers to axios.post call

4๐Ÿ‘

โœ…

Try to create a fetch function and use it inside .call.

function* createPostSaga(action) {
  const token = yield select(selectToken);
  const headerParams = {
    "Authorization": `JWT ${token}`
  };

  const apiCall = () => {
    return axios.post('/posts', {
      action.payload // only if not an object. Otherwise don't use outer {},
    },
    headerParams: headerParams,
   ).then(response => response.data)
    .catch(err => {
      throw err;
    });
  }

  console.log(token, headerParams);
  try {
    yield call(apiCall);
    yield call(getPosts());
  } catch (error) {
    console.log(error);
  }
}
๐Ÿ‘คKort

2๐Ÿ‘

You have to call the function like this.

function* createPostSaga(action) {
  const token = yield select(selectToken);
  const headerParams = {
    Authorization: `JWT ${token}`
  };
  console.log(token, headerParams);
  try {
    yield call(axios.post, "/posts/", action.payload, {headers:headerParams});
    yield call(getPosts());
  } catch (error) {
    console.log(error);
  }
}
๐Ÿ‘คRenato N_

Leave a comment