I'm working on my first react/redux app and I'm not sure where I should call sessionStorage.setItem(). I'm currently storing user credentials from a loginUserSuccess() action but I'm not sure this is where I should be doing that. Furthermore, I'm using fetch to make requests and would like to add the user's authToken to all requests. I was looking into fetch-intercept but not much documentation is provided for modifying headers.
actions/loginActions.js
export function loginUser(user) {
return function(dispatch) {
return LoginApi.login(user).then(creds => {
dispatch(loginUserSuccess(creds));
}).catch(error => {
throw(error);
});
};
}
export function loginUserSuccess(creds) {
sessionStorage.setItem('credentials', JSON.stringify(creds));
return {
type: types.LOGIN_USER_SUCCESS,
state: creds
}
}
api/packageApi.js
class PackageApi {
// called on successful login
static getAllPackages() {
const request = new Request('/my/endpoint', {
method: 'GET',
headers: new Headers({
'AUTHORIZATION': `Bearer ${JSON.parse(sessionStorage.credentials).authToken}`
})
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
}
export default PackageApi;