[ReactNative] AsyncStorage๋กœ ๋ฐ์ดํ„ฐ ์ €์žฅํ•˜๊ธฐ
728x90

Today, What I learned?

์›น์ด๋‚˜ ์•ฑ์ด๋‚˜ ์–ด๋–ค ์ •๋ณด๋“ค์„ ๋กœ์ปฌ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ €์žฅํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋‹ค.

ํˆฌ๋‘๋ฆฌ์ŠคํŠธ๋ฅผ ์™•์ฐฝ ๋งŒ๋“ค๊ณ  ์žˆ์œผ๋‹ˆ ์ด๊ฑธ ์˜ˆ์‹œ๋กœ ๋“ค์ž๋ฉด,

์ƒˆ๋กœ๊ณ ์นจํ•˜๊ฑฐ๋‚˜ ์ข…๋ฃŒ ํ›„ ๋‹ค์‹œ ์‹คํ–‰ํ–ˆ์„ ๋•Œ ์ „์— ์ž‘์„ฑํ–ˆ๋˜ ๋ฆฌ์ŠคํŠธ๊ฐ€ ๋‚จ์•„์žˆ๋Š” ๊ฒƒ์ด ํ•„์ˆ˜!

๋ธŒ๋ผ์šฐ์ €์— ๋กœ์ปฌ ์Šคํ† ๋ฆฌ์ง€๊ฐ€ ์žˆ๋‹ค๋ฉด, React Native์—์„œ๋Š” AsyncStorage๋ฅผ ์ด์šฉํ•ด์„œ ์ €์žฅํ•ด๋ณผ ์ˆ˜ ์žˆ๋‹ค.

 

 

Async Storage

๊ณต์‹ ๋ฌธ์„œ์— ๋“ค์–ด๊ฐ€ ๋ณด๋ฉด ์•„๋ž˜์™€ ๊ฐ™์€ ๋‚ด์šฉ์ด ์žˆ๋‹ค.

 

Data storage system for React Native.

๋ฆฌ์•กํŠธ ๋„ค์ดํ‹ฐ๋ธŒ๋ฅผ ์œ„ํ•œ ๋ฐ์ดํ„ฐ ์Šคํ† ๋ฆฌ์ง€!

 

์ €์žฅํ•˜๊ฑฐ๋‚˜ ๋ถˆ๋Ÿฌ์˜ค๋Š” ๋ฐฉ์‹์ด Local Storage๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ์‹๊ณผ ๊ฑฐ์˜ ํก์‚ฌํ•˜๋‹ค.

 

https://react-native-async-storage.github.io/async-storage/

 

Async Storage | Async Storage

Homepage for React Native Async Storage project

react-native-async-storage.github.io

 

 

์„ค์น˜

npm install @react-native-async-storage/async-storage

์„ค์น˜ ํ›„ import ํ•ด์„œ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

 

 

์‚ฌ์šฉ

์ด๋ฆ„๋ถ€ํ„ฐ๊ฐ€ Async Storage ์ธ ๊ฒƒ์ฒ˜๋Ÿผ, async - await๋ฅผ ์ด์šฉํ•ด์„œ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๊ณ  ๊ฐ€์ ธ์˜จ๋‹ค.

์ €์žฅํ•˜๊ณ  ๋ถˆ๋Ÿฌ์˜ค๋Š” ๋ฐฉ์‹์€ getItem, setItem์œผ๋กœ ๋กœ์ปฌ ์Šคํ† ๋ฆฌ์ง€์™€ ๋™์ผํ•œ ๋ฐฉ์‹์ด๋‹ค.
๋‹ค๋งŒ ๋ฐฐ์—ด์ด๋‚˜ ๊ฐ์ฒด๋ฅผ setItem ๋ฉ”์„œ๋“œ๋กœ ์ €์žฅํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” JSON.parse() ๋กœ ๊ฐ€์ ธ์˜ค๊ณ  JSON.stringify()๋กœ ์ €์žฅํ•ด์•ผ ํ•˜๋Š” ์ ์ด ์žˆ์—ˆ๋‹ค.

 

getItem

 const getTodos = async () => {
      const allTodos = await AsyncStorage.getItem('todos');
      const currentCategory = await AsyncStorage.getItem('category');

      setTodos(JSON.parse(allTodos));
      setCategory(currentCategory ?? 'js');
    };

 

 

setItem

  const saveTodos = async () => {
      await AsyncStorage.setItem('todos', JSON.stringify(todos));
      await AsyncStorage.setItem('category', category);
    };

 

 

 

์ ์šฉํ–ˆ์„ ๋•Œ ์ƒˆ๋กœ๊ณ ์นจํ•ด๋„ ๋ฐ์ดํ„ฐ๊ฐ€ ๋‚จ์•„์žˆ๋Š” ๋ชจ์Šต์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

ํฌ๊ฒŒ ์ค‘์š”ํ•˜์ง€ ์•Š์€ ๋ฐ์ดํ„ฐ์ด๊ฑฐ๋‚˜, ๊ฐ„๋‹จํ•˜๊ฒŒ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•  ๋•Œ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค!

 

728x90