From 281a7ac90c9f676d7dd68f49f2d62f5693dfe64b Mon Sep 17 00:00:00 2001 From: Paul Bienkowski Date: Sun, 14 Feb 2021 19:21:34 +0100 Subject: [PATCH] Cleanup API calls --- src/api.js | 27 +++++++++++++++++- src/pages/TrackPage/TrackComments.tsx | 33 ++++++++++++++++----- src/pages/TrackPage/index.tsx | 41 ++++++++++++++++++++------- src/pages/TracksPage.tsx | 10 +++---- 4 files changed, 88 insertions(+), 23 deletions(-) diff --git a/src/api.js b/src/api.js index 8b7784d..2ccc9a1 100644 --- a/src/api.js +++ b/src/api.js @@ -1,3 +1,5 @@ +import {stringifyParams} from 'query' + class API { setAuthorizationHeader(authorization) { this.authorization = authorization @@ -12,7 +14,30 @@ class API { }, }) - return await response.json() + if (response.status === 200) { + return await response.json() + } else { + return null + } + } + + async post(url, {body: body_, ...options}) { + const body = typeof body_ !== 'string' ? JSON.stringify(body_) : body_ + return await this.fetch(url, {...options, body, method: 'post', + headers: { + ...(options.headers || {}), + 'Content-Type': 'application/json', + }, + }) + } + + async get(url, {query, ...options} = {}) { + const queryString = query ? stringifyParams(query) : null + return await this.fetch(url + (queryString ? '?' + queryString : ''), {method: 'get', ...options}) + } + + async delete(url, options = {}) { + return await this.get(url, {...options, method: 'delete'}) } } diff --git a/src/pages/TrackPage/TrackComments.tsx b/src/pages/TrackPage/TrackComments.tsx index 4692af5..de2dbc9 100644 --- a/src/pages/TrackPage/TrackComments.tsx +++ b/src/pages/TrackPage/TrackComments.tsx @@ -3,7 +3,23 @@ import {Segment, Form, Button, Loader, Header, Comment} from 'semantic-ui-react' import {FormattedDate} from 'components' -export default function TrackComments({comments, login, hideLoader}) { +function CommentForm({onSubmit}) { + const [body, setBody] = React.useState('') + + const onSubmitComment = React.useCallback(() => { + onSubmit({body}) + setBody('') + }, [onSubmit, body]) + + return ( +
+ setBody(e.target.value)} /> +