store

sting01·2023년 3월 6일
0

svelte

목록 보기
14/18

app

<script>
	import { onMount } from 'svelte';
	import storeHobs from './store.js';

	let hobs = [];
	let hobInput;
	let isLoading = false;

	isLoading = true;
	let getHobs = fetch(
		'https://svelte-max-658a0-default-rtdb.firebaseio.com/hobbies.json',
	)
		.then(res => {
			if (!res.ok) {
				throw new Error('failed');
			}

			return res.json();
		})
		.then(data => {
			isLoading = false;
			storeHobs.setHob(Object.values(data));
			// hobs = Object.values(data);
			let keys = Object.keys(data);

			for (const key of data) {
				console.log(key, data[key]);
			}

			return hobs;
		})
		.catch(err => {
			isLoading = false;
			console.log(err);
		});

	const add = () => {
		// hobs = [...hobs, hobInput.value];

		storeHobs.addHob(hobInput.value);

		fetch(
			'https://svelte-max-658a0-default-rtdb.firebaseio.com/hobbies.json',
			{
				method: 'POST',
				body: JSON.stringify(hobInput.value),
				headers: {
					'Content-Type': 'application/json',
				},
			},
		)
			.then(res => {
				isLoading = false;
				if (!res.ok) {
					throw new Error('failed');
				}

				alert('저장');
			})
			.catch(err => {
				isLoading = false;
				console.log(err);
			});
	};
</script>

<style>
</style>

<label for="hobId">hobs</label>
<input type="text" id="hobId" bind:this="{hobInput}" />
<button on:click="{add}">add hobs</button>

{#if isLoading}
	<p>isLoading</p>
{/if}
<ul>
	{#each $storeHobs as item}
		<li>{item}</li>
	{/each}
</ul>

<!-- {#await getHobs}
	<p>isLoading</p>
{:then dataHobs}
	console.log(dataHobs)
	<ul>
		{#each dataHobs as item}
			<li>{item}</li>
		{/each}
	</ul>
{:catch error}
	<p>error.massage</p>
{/await} -->

store.js

import { writable } from 'svelte/store';

const hobbies = writable([]);

const customStore = {
	subscribe: hobbies.subscribe,
	setHob: items => {
		hobbies.set(items);
	},
	addHob: hob => {
		hobbies.update(items => {
			return items.concat(hob);
		});
	},
};

export default customStore;

store 작성 시 writable, readable , subscribe 필요
기본 fetch api 활용
svelte 기본 내
{#await} {:then} {:catch} 태그 활용 가능

0개의 댓글