From 8d0b32f8dfe45291426e58f6bf20cffac8dab6e7 Mon Sep 17 00:00:00 2001 From: Joseph Ditton Date: Tue, 23 Nov 2021 14:04:12 -0700 Subject: adds api, guard, tailwind --- client/utils/use_api.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 client/utils/use_api.js (limited to 'client/utils/use_api.js') diff --git a/client/utils/use_api.js b/client/utils/use_api.js new file mode 100644 index 0000000..aab0293 --- /dev/null +++ b/client/utils/use_api.js @@ -0,0 +1,37 @@ +import { useRef } from 'react'; + +export const useApi = (authToken) => { + const apiRef = useRef(new Api()); + apiRef.current.authToken = authToken; + return apiRef.current; +}; + +export class Api { + authToken = null; + + makeRequest(url, method, body) { + return fetch(url, { + method, + headers: { + Authorization: `Bearer ${this.authToken}`, + }, + body, + }).then((res) => res.json()); + } + + get(url) { + return this.makeRequest(url, 'GET'); + } + + post(url, body = {}) { + return this.makeRequest(url, 'POST', body); + } + + put(url, body = {}) { + return this.makeRequest(url, 'PUT', body); + } + + del(url) { + return this.makeRequest(url, 'DELETE'); + } +} -- cgit v1.2.3-70-g09d2