Skip to content

Instantly share code, notes, and snippets.

@xXcarlos117Xx2
Last active April 4, 2024 23:27
Show Gist options
  • Save xXcarlos117Xx2/c0d6a947231ba6c6badfc52e43c00510 to your computer and use it in GitHub Desktop.
Save xXcarlos117Xx2/c0d6a947231ba6c6badfc52e43c00510 to your computer and use it in GitHub Desktop.
API Handler in flux with options and token manager
// flux.js
const getState = ({ getStore, getActions, setStore }) => {
return {
store: {},
actions: {
// API Handler
APICall: async (url, options) => {
try {
const response = await fetch(getStore().baseURL + url, options);
if (!response.ok) {
console.error('Error: ' + response.status, response.statusText);
return response.status;
};
return await response.json();
} catch (error) {
console.error('Error in fetch:', error);
return null;
};
},
// Options / Token manager
optionsMethod: async (method, data = null) => {
const headers = { 'Content-Type': 'application/json' }
if (localStorage.getItem('access_token')) { // Change this where access_token is saved
headers['Authorization'] = `Bearer ${localStorage.getItem('access_token')}` // Change this to handle, this example is with "Bearer authentication"
};
const options = {
method: method,
headers: headers,
};
if (data) {
options.body = JSON.stringify(data);
};
return options;
},
}
};
};
export default getState;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment