-
[ React Native ] AsyncStorage key 값 저장Application/React Native 2025. 10. 6. 21:40반응형
web에서는 localstorage가 존재해서 사용자를 기준으로 저장하는게 아니라면 localStorage를 활용하여 간단한 데이터를 저장할 수 있다.
react native도 마찬가지로 asyncStoage가 존재하며 여기에 localStorage처럼 key, value형태로 저장이 가능하다.
앱 테마 설정경우 이를 활용해서 저장하면 편하게 관리할 수 있기때문에
AsyncStorage를 활용하여 데이터를 저장
Initialized
async-storage 패키지를 설치
npm install @react-native-async-storage/async-storage
Useage
설정한 테마를 저장할 것이므로 테마 값 관리 같은 경우는 아래 글을 참고
https://yumedev.tistory.com/90
[ React Native ] 다크모드 테마설정 간단하게 처리하기
앱을 만들면서 항상 테마 설정을 하는데 react native의 테마 설정하는 방법을 찾아보는데 대부분이 hook을 이용해서 구현하는 방법들이 대부분 이었다. 근데 이러면 내가 원하는 곳에 원하는 색을
yumedev.tistory.com
이제 asyncStorage 저장 및 가져오는 함수를 구현
key값은 상수값으로 관리
import AsyncStorage from "@react-native-async-storage/async-storage"; import {APP_THEME_KEY} from "@/constant/storage.ts"; import {selectTheme} from "@/constant/setting.ts"; const setThemeStorage = async (value: keyof typeof selectTheme) => { try { await AsyncStorage.setItem(APP_THEME_KEY,value as string) } catch (e) { console.error('저장 실패',e) } } const getThemeStorage = async () => { try { const value = await AsyncStorage.getItem(APP_THEME_KEY) if(value !== null) { return value } } catch (e) { console.error('저장 실패',e) } return 'white' } export {setThemeStorage, getThemeStorage}
이후 이전 테마 변경 함수에 setThemeStorage함수를 추가하여
테마가 변경될때마다 storage에 저장
import {selectTheme} from "@/constant/setting.ts"; import {setThemeStorage} from "@/storage/themeStorage.ts"; ...생략... export let theme = colortheme['white'] export const setTheme = async (value: keyof typeof selectTheme) => { theme = colortheme[value] await setThemeStorage(value) }
이후 저장한 값은 app이 처음 실행될때 현재 테마 값을 가져와야하기 때문에 app.tsx파일에서 useEffect로 처음 앱 실행시에 storage에 저장된 값을 가져온다
이후 가져온 값을 store에 저저장해주고, 테마 변경처럼 setTheme함수로 테마 색상값을 변경한다.
기본값는 화이트 테마로 하기 위해 값이 없다면 white로 테마 설정
function App() { const appStore = useAppStore() useEffect(() => { ( async () => { const storageTheme = await getThemeStorage() if(storageTheme) { appStore.setTheme(storageTheme) await setTheme(storageTheme) return } appStore.setTheme('white') await setTheme('white') })() },[]) return ( <SafeAreaProvider> <NavigationContainer> <BottomNavigation/> </NavigationContainer> </SafeAreaProvider> ); }
그럼 테마 변경 후 새로고침 해도 테마가 잘 적용되서 나오는 것을 확인 할 수 있다.
728x90반응형'Application > React Native' 카테고리의 다른 글
[ React Native ] 직접 Popup 만들기 (0) 2025.10.08 [ React Native ] Stack Navigation (0) 2025.10.08 [ React Native ] 다크모드 테마설정 간단하게 처리하기 (0) 2025.10.06 [ React Native ] react-navigation bottom-tabs (0) 2025.10.05 [ React Native ] Svg Icon Component (0) 2025.10.05