Skip to content

값 저장하기

setItem

setItem 함수는 모바일 앱의 로컬 저장소에 문자열 데이터를 저장해요. 주로 앱이 종료되었다가 다시 시작해도 데이터가 유지되어야 하는 경우에 사용해요.

시그니처

typescript
function setItem(key: string, value: string): Promise<void>;

파라미터

  • key필수 · string

    저장할 아이템의 키를 입력해요.

  • value필수 · string

    저장할 아이템의 값을 입력해요.

반환 값

  • Promise<void>

    아이템을 성공적으로 저장하면 아무 값도 반환하지 않아요.

예제

my-key에 아이템 저장하기

tsx
import { Storage } from '@apps-in-toss/web-framework';
import { Button, Text } from '@toss-design-system/mobile';
import { useState } from 'react';

const KEY = 'my-key';

function StorageClearButton() {
  const [storageValue, setStorageValue] = useState<string | null>(null);

  async function handleSet() {
    await Storage.setItem(KEY, 'my-value');
  }

  async function handleGet() {
    const storageValue = await Storage.getItem(KEY);
    setStorageValue(storageValue);
  }

  async function handleRemove() {
    await Storage.removeItem(KEY);
  }

  return (
    <>
      <Text>{storageValue}</Text>
      <Button onClick={handleSet}>저장하기</Button>
      <Button onClick={handleGet}>가져오기</Button>
      <Button onClick={handleRemove}>삭제하기</Button>
    </>
  );
}
tsx
import { Storage } from '@apps-in-toss/framework';
import { Button, Text } from '@toss-design-system/react-native';
import { useState } from 'react';

const KEY = 'my-key';

function StorageClearButton() {
  const [storageValue, setStorageValue] = useState<string | null>(null);

  async function handleSet() {
    await Storage.setItem(KEY, 'my-value');
  }

  async function handleGet() {
    const storageValue = await Storage.getItem(KEY);
    setStorageValue(storageValue);
  }

  async function handleRemove() {
    await Storage.removeItem(KEY);
  }

  return (
    <>
      <Text>{storageValue}</Text>
      <Button onPress={handleSet}>저장하기</Button>
      <Button onPress={handleGet}>가져오기</Button>
      <Button onPress={handleRemove}>삭제하기</Button>
    </>
  );
}