separating api utils from app logic

This commit is contained in:
2022-05-29 13:17:54 -05:00
parent d4121586cd
commit 9e295dde68
9 changed files with 39 additions and 33 deletions

View File

@@ -1,39 +1,15 @@
import { useState } from 'react'
import { getAllUsers, registerNewUser } from './util/apiUtils';
import { userInfo } from './types/main';
import './App.css'
function App() {
const [response, setResponse] = useState<any>(undefined);
type userInfo = {
email: string;
id?: number;
name: string;
password: string;
}
const doAPICall = async () => {
let serverCall = await fetch('http://localhost:8088/users')
.then(res => res.json());
serverCall && setResponse(serverCall);
}
const addSampleUser = async () => {
let newUser: userInfo = {
email: 'another@email.com',
name: "still another person",
password: "dumb_password"
}
let thing = await fetch('http://localhost:8088/register', {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(newUser)
});
if (thing.ok) alert('User added successfully.');
let newUser: userInfo = {
email: 'anotherperson@email.com',
name: "one more person",
password: "dumb_password"
}
return (
@@ -50,8 +26,8 @@ function App() {
})}
</div>
<button onClick={doAPICall}>API call?</button>
<button onClick={addSampleUser}>Add sample user</button>
<button onClick={() => getAllUsers().then(res => setResponse(res))}>API call?</button>
<button onClick={() => registerNewUser(newUser).then(res => alert(res))}>Add sample user</button>
</div>
)
}

View File

View File

View File

View File

View File

6
client/src/types/main.d.ts vendored Normal file
View File

@@ -0,0 +1,6 @@
export type userInfo = {
email: string;
id?: number;
name: string;
password: string;
}

View File

@@ -0,0 +1,20 @@
import { userInfo } from '../types/main';
export const getAllUsers = async () => {
let serverCall = await fetch('http://localhost:8088/users')
.then(res => res.json());
return serverCall;
}
export const registerNewUser = async (user: userInfo) => {
let serverCall = await fetch('http://localhost:8088/register', {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(user)
});
if (serverCall.ok) return 'User added successfully.';
}

View File

@@ -14,7 +14,11 @@
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
"jsx": "react-jsx",
"typeRoots": [
"./src/types/main.d.ts",
"./node_modules/@types"
]
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]