0

I am using redux-saga. When dispatch is executed, functions such as likePost and addPost are executed.

Then every time I use AsyncStorage.getItem to fetch the token. In other words, it overlaps

      const token = yield AsyncStorage.getItem('tokenstore');

And because i have to use jwt token

     {},
        {
          headers: {Authorization: `Bearer ${token}`},
        },

i need to keep passing headers like this to the api. This is also overlaps

How can I use this without redundancy, or how can I use it most conveniently?

this is my code

(saga/post.js)

    import {all, fork, put, takeLatest, throttle, call} from 'redux-saga/effects';
    import axios from 'axios';
    import AsyncStorage from '@react-native-async-storage/async-storage';

    function* likePost(action) {
      try {
        const token = yield AsyncStorage.getItem('tokenstore');
        const result = yield call(likePostAPI, action.data, token);
        // console.log("result:",result);
        yield put({
          type: LIKE_POST_SUCCESS,
          data: result.data,
        });
      } catch (err) {
        console.error(err);
      }
    }

    function likePostAPI(data, token) {
      return axios.patch(
        `/post/${data}/like`,
        {},
        {
          headers: {Authorization: `Bearer ${token}`},
        },
      );
    }


    function addPostAPI(action, token) {
      return axios.post('/post', action, {
        headers: {Authorization: `Bearer ${token}`},
      });
    }

    function* addPost(action) {
      try {
        const token = yield AsyncStorage.getItem('tokenstore');
        const result = yield call(addPostAPI, action, token);
        yield put({
          type: ADD_POST_SUCCESS,
          data: result.data,
        });
      } catch (err) {
        console.error(err);
      }
    }



    function* watchLikePost() {
      yield takeLatest(LIKE_POST_REQUEST, likePost);
    }

    function* watchAddPost() {
      yield takeLatest(ADD_POST_REQUEST, addPost);
    }



    export default function* postSaga() {
      yield all([

        fork(watchLikePost),
        fork(watchAddPost),
      ]);
    }

(saga/index.js)

    import { all, fork } from 'redux-saga/effects';
    import axios from 'axios';

    import postSaga from './post';
    import userSaga from './user';


    axios.defaults.baseURL = 'http://10.0.2.2:3065';

    export default function* rootSaga() {
      yield all([
        fork(postSaga),
        fork(userSaga),
      ]);
    }
user15322469
  • 841
  • 1
  • 8
  • 31

1 Answers1

1

Instead of using axios directly, you could make a new axios instance and use it instead. That way you could intercept every request and add the JWT token to the request headers.

custom-axios.js:

import axios from 'axios';

const AxiosInstance = axios.create({
  // A good thing is to set your baseURL here
  baseURL: 'https://your-api.com',
});

AxiosInstance.interceptors.request.use(async (cfg) => {
  // Get your token from the storage
  const token = await AsyncStorage.getItem('tokenstore');

  // If the token exists, attach it to the current request's Authorization header
  if (token) {
    cfg.headers.Authorization = token;
  }

  return cfg;
});

export default AxiosInstance;

And then use it inside of your sagas

(saga/post.js):

import axiosInstace from '../custom-axios.js'

...
function addPostAPI(action, token) {
  // Now when using axiosInstace, you don't have to add the token to your headers
  // because it will handle it internally for every request made with this instance
  return axiosInstace.post('/post', action);
}
...
Kapobajza
  • 2,254
  • 15
  • 22
  • i updated my post. but i already use base url.. in this case how can i add and apply your code? – user15322469 Apr 17 '21 at 09:24
  • You could also add the `Authorization` header to the `axios.defaults` property. Look at the 2nd item of [this](https://stackoverflow.com/a/43052288/5049799) answer. – Kapobajza Apr 17 '21 at 09:28