I am new in this topic (data store in asyncStorage) I want to store my theme color in asyncStorage because when user close the app them will remain same as they selected.
I am able to change the theme on click but there were some issue on click.
I have to click twice to change theme(eq. : if there is light theme then I have to click twick like light to dark and again light then I am able to get dark theme and If there is dark theme then I have to click twice to change theme like dark to light to dark then I will get light theme
This is my Context.js file
import React, {createContext, useEffect, useState} from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
const Context = createContext();
export const TProvider = ({children}) => {
const [theme, setTheme] = useState('light');
const toggleTheam = async () => {
const DataClr = await AsyncStorage.getItem('Color');
setTheme(theme === 'light' ? 'dark' : 'light');
AsyncData();
};
const AsyncData = async () => {
await AsyncStorage.setItem('Color', theme);
};
return (
<Context.Provider value={{theme, toggleTheam, setTheme}}>
{children}
</Context.Provider>
);
};
export default Context;
and this is my First.js file from where I change my theme on Press
import React, {useContext, useEffect} from 'react';
import {View, Button, Text} from 'react-native';
import Context from './Context';
import AsyncStorage from '@react-native-async-storage/async-storage';
const First = ({navigation}) => {
const {theme, toggleTheam, setTheme} = useContext(Context);
useEffect(async () => {
const Data = await AsyncStorage.getItem('Color');
if (Data) {
setTheme(Data);
}
}, []);
console.log('Theme==>', theme);
return (
<View
style={{
height: '100%',
padding: 20,
backgroundColor: theme === 'light' ? '#fff' : '#000',
}}>
<Text
style={{
textAlign: 'center',
color: theme === 'light' ? '#000' : '#fff',
}}>
First Screen
</Text>
<Button title="Change Color" onPress={toggleTheam} />
<Button
title="Go to next Screen"
onPress={() => {
navigation.navigate('Second');
}}
/>
</View>
);
};
export default First;
I have tried to store my theme color in Context.js file but I am not able to get that theme when I refresh the app
2
Answers
I have use this to solve this funcnality. and I am able to store useContext data in asyncStorage.
I created this example without using
useContext
. But you can adapt it later if it works. I think the problem is that state is asynchronous and you are saving to the async storage immediately after setting the newstate
.Please try this: