I'm currently building a react-native application that uses react-redux to manage state. I'm attempting to dedup some authentication related logic by putting it into a service that isn't an extension of React's Component
class. When a user logs in to the app, they are returned a user_token
to validate subsequent API calls to the server. This token is stored in the auth
reducer, so it would be available in a call of mapStateToProps
via state.auth.user_token
. I've defined a function in src/utils/fetch.js
that performs API calls for me:
export function fetchAPI(endpoint, method = 'GET', data) {
let url = 'http:localhost:3000/api/' + endpoint;
let headers = { 'User-Token': 'XXXXXX' };
if (method === 'POST') {
headers['content-type'] = 'application/json';
}
let options = {
method: method,
headers: headers,
mode: 'cors' // no-cors, cors, *same-origin
};
if (data) {
options.body = JSON.stringify(data);
}
return fetch(url, options).then((response) => {
...
I'm wondering if there is a graceful / normal way of making this utility service aware of the values inside of state
. I don't want to explicitly extract that property in every component that makes authenticated API calls - I'd basically have to do it everywhere and it feels redundant and verbose. Changing the method signature to accept this parameter feels bad:
export function fetchAPI(user_token, endpoint, method = 'GET', data) {
^^^^^^^^^^ doesn't change while someone is logged in
But something like this feels better:
import storeProvider from './storeProvider';
export function fetchAPI(user_token, endpoint, method = 'GET', data) {
const user_token = storeProvider.getUserToken();
... (go do great stuff with user_token)
Is there a conventional way to do this? Has anyone seen this sort of extracting of state
into something that isn't a Container?