HarishJangra/react-native-easy-starter

selected theme resets after reloading app

iamhaaamed opened this issue · 4 comments

Hi,
How can I save the selected theme in AsyncStorage so that when the user close and reopens the app the selected theme still showing? like the one implemented for i18n.

Yes you can use asyncstorage inside themecontext you can get theme from storage
At first or default if not available in storage

is this correct?

`import React, {useMemo} from 'react';
import defaultTheme, {nightTheme} from '..';
import useStorage from '../../services/AsyncStorage';

const ThemeContext = React.createContext();

export const ThemeProvider = ({theme, children}) => {
const [themeObj, changeTheme] = useStorage('@selectedTheme', defaultTheme);

const setTheme = (t) => {
changeTheme(t);
};

const contextValue = useMemo(
() => ({
theme: themeObj,
changeTheme: (t) => setTheme(t),
toggleTheme: () => {
if (themeObj.id === 1) {
setTheme(nightTheme);
} else {
setTheme(defaultTheme);
}
},
}),
[themeObj, setTheme],
);

return (
<ThemeContext.Provider value={contextValue}>
{children}
</ThemeContext.Provider>
);
};

export default ThemeContext;
`

I think so .. just check and log the themeobj returned from storage. You will get to know if the code works

You can just put id of theme in storage for easier access and set the object according to id of theme.