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),
]);
}