Created
September 25, 2019 07:42
-
-
Save indatawetrust/a33e5ee0dd089579d8b4f0d295c246b9 to your computer and use it in GitHub Desktop.
httpClient for react-admin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {fetchUtils} from 'react-admin'; | |
const httpClient = (url, options = {}) => { | |
if (!options.headers) { | |
options.headers = new Headers({Accept: 'application/json'}); | |
} | |
const token = localStorage.getItem('jwt'); | |
options.headers.set('Authorization', `Bearer ${token.replace(/"/g, '')}`); | |
return fetchUtils.fetchJson(url, options); | |
}; | |
export default (method, url, params = {}) => { | |
url = url[0] != '/' ? `/${url}` : url; | |
if (params.body && typeof params.body === "object") { | |
params.body = JSON.stringify(params.body) | |
} | |
return httpClient(`${process.env.REACT_APP_API_URL}${url}`, { | |
method: method, | |
...params, | |
}).then(data => { | |
try { | |
data.body = JSON.parse(data.body); | |
} catch (error) {} | |
return data; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment