Skip to content

Commit

Permalink
Load user from backend, thanks to the 🦫
Browse files Browse the repository at this point in the history
  • Loading branch information
yannikinniger committed Oct 28, 2023
1 parent 8dc355e commit 19e9e9f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
15 changes: 9 additions & 6 deletions src/model/user.store.ts
@@ -1,13 +1,16 @@
import { writable } from 'svelte/store';
import { get } from '../utils/rest.utils';
import type { User, UserStoreData } from './user.model';

const mockUser: User = {
id: '1',
name: '1',
};

export const userStore = writable<UserStoreData>(null);

export const loadUserByApartmentNumber = (apartmentNumber: number) => {
userStore.set(mockUser);
get<{ data: User[] }>('/users')
.then((response) => response.data)
.then((users) => {
const user = users.find(
(user) => user.name === apartmentNumber.toString()
);
userStore.set(user ?? null);
});
};
10 changes: 5 additions & 5 deletions src/utils/rest.utils.ts
@@ -1,15 +1,15 @@
import { BASE_URL } from '../consts';

export const get = (endpoint: string) => {
fetch(`${BASE_URL}${endpoint}`, {
export const get = async <T>(endpoint: string) => {
return fetch(`${BASE_URL}${endpoint}`, {
method: 'GET',
}).then((response: Response) => response.json());
}).then((response: Response) => response.json() as T);
};

export const post = <T>(endpoint: string, body: T): Promise<T> => {
export const post = async <T>(endpoint: string, body: T): Promise<T> => {
const json = JSON.stringify(body);
return fetch(`${BASE_URL}${endpoint}`, {
method: 'POST',
body: json,
}).then((response: Response) => response.json());
}).then((response: Response) => response.json() as T);
};

0 comments on commit 19e9e9f

Please sign in to comment.