Ollie
Ollie

Reputation: 243

Async Storage to store theme in React native

I've set up a theme using context but I want to save the theme after the user has restarted the app. I'm new to data storage so I would need some help in how to write this code in Async Storage for specific case as I'm a bit confused on how to get it working. Thank you! (I've cleaned up a lot of code to only include the relevant things, so thats why it looks slim)

Under App.js

import ThemeContext, {themes} from './contexts/ThemeContext';
const [selectedTheme, setSelectedTheme] = useState(themes.arctic)

const changeTheme = (theme) =>{
  if (theme === "dark"){
  setSelectedTheme(themes.dark)} 
  else if (theme === "light") {
  setSelectedTheme(themes.light)
  }
  else if (theme === "red") {
  setSelectedTheme(themes.red)
  }

<ThemeContext.Provider value={{selectedTheme, changeTheme}}>
  <....>
  <Stack.Screen name="Settings" component={Settings}/>

Under Settings (if this code is needed, this is where I call the changeTheme function)

const handlePress = (theme) => {
    changeTheme(theme)}


<ThemeBadge color="white" onPress={()=>handlePress("light")}/>
<ThemeBadge color="black" onPress={()=>handlePress("dark")}/>
<ThemeBadge color="red" onPress={()=>handlePress("red")}/>

Upvotes: 1

Views: 1096

Answers (1)

Fiston Emmanuel
Fiston Emmanuel

Reputation: 4859

As you're using Expo, install expo-secure-store. Let we use custom hook to easily manage app theme preference.

import * as SecureStore from "expo-secure-store";
import { useeEffect, useState } from "react";

function useAppTheme() {
  const [theme, setTheme] = useTheme("light");

  async function updateTheme(key = "theme", value) {
    await SecureStore.setItemAsync(key, String(value).toString());
  }

  async function getTheme(key = "theme") {
    let result = await SecureStore.getItemAsync(key);
    if (result) {
      setTheme(result);
    } else {
      console.error("App could not get theme.");
    }
  }

  useEffect(() => getValueFor("theme"), []);

  return { theme, getTheme, updateTheme };
}

export default useAppTheme;

later in code, use hook

const App = ()=>{
const {theme, updateTheme} = useAppTheme

const changeTheme = async (theme) =>{
  if (theme === "dark"){
await updateTheme("theme",themes.dark)

  setSelectedTheme(themes.dark)} 
  else if (theme === "light") {

await updateTheme("theme",themes.light)
  setSelectedTheme(themes.light)
  }
  else if (theme === "red") {

await updateTheme("theme",themes.red)
  setSelectedTheme(themes.red)
  }

<ThemeContext.Provider value={{selectedTheme, changeTheme}}>
  <....>
  <Stack.Screen name="Settings" component={Settings}/>


}


Upvotes: 2

Related Questions