Skip to content

Commit

Permalink
feat: render api data
Browse files Browse the repository at this point in the history
  • Loading branch information
robzarel committed Apr 26, 2023
1 parent 5d4cc22 commit 65788cf
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 16 deletions.
33 changes: 17 additions & 16 deletions src/App.tsx
@@ -1,24 +1,25 @@
import React from 'react';
import logo from './logo.svg';
import React, { useEffect, useState } from 'react';

import api from './api';
import type { RESPONSE_DATA } from './api';

import './App.css';

function App() {
const [data, setData] = useState<RESPONSE_DATA>();

useEffect(() => {
const fetchData = async () => {
const response = await api.get.data();
setData(response);
};

fetchData();
}, [])

return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
{data ? <p>{data.greeting}</p>: "no data"}
</div>
);
}
Expand Down
28 changes: 28 additions & 0 deletions src/api/index.ts
@@ -0,0 +1,28 @@
import getEndpoints from '../server/db';

const endpoints = getEndpoints();

type ENDPOINTS = keyof typeof endpoints;
type RESPONSE_DATA = {
greeting: string
};

const getJson = async <T>(endpoint: ENDPOINTS): Promise<T> => {
const path = `http://localhost:3001/api/${endpoint}`;
const response = await fetch(path);

return await response.json();
};

type API = {
get: {
data: () => Promise<RESPONSE_DATA>
}
};
const api: API = {
get: {
data: () => getJson<RESPONSE_DATA>('data')
}
}
export type { RESPONSE_DATA, ENDPOINTS }
export default api;

0 comments on commit 65788cf

Please sign in to comment.