i'm sorry for the disturbance,
i'm a trying React Native for the first time ( I'm a Full Stack Engineer React NodeJS ),
i tried by differents tips to put AsyncStorage.getItem inside my state, then display in the map,
but everytime, "Error map undefined", but if i put the value inside my State Array, it's working,
i tried with JSON Stringify, JSON Parse... Like in WEB,
but not working...
Here is my code :
import { useEffect, useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import RadioForm from 'react-native-simple-radio-button';
import AsyncStorage from '@react-native-async-storage/async-storage';
const SelectOption = () => {
const [value, setValue] = useState([]);
const saveOption = (item) => {
try {
setValue([...value, {name: item, id: Math.random()}]);
} catch (e) {
console.log(e);
}
};
useEffect(() => {
AsyncStorage.setItem('option', JSON.stringify(value));
}, [value]);
// Put GetItem in the state
useEffect(() => {
const getOption = async () => {
try {
const jsonValue = await AsyncStorage.getItem('option');
if (jsonValue !== null) {
setValue(JSON.parse(jsonValue));
}
} catch (e) {
console.log(e);
}
};
getOption();
}, []);
AsyncStorage.getItem('option').then((value) => {
console.log(value);
});
const radioProps = [
{label: 'Option 1', value: 'option1'},
{label: 'Option 2', value: 'option2'},
{label: 'Option 3', value: 'option3'}
];
return (
<View style={styles.sectionContainer}>
<RadioForm
radio_props={radioProps}
initial={0}
onPress={(value) => {
saveOption(value);
}}
/>
{value.map((item) => {
return <Text key={item.id}>{item.name}</Text>;
})
}
</View>
);
};
const styles = StyleSheet.create({
sectionContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
export default SelectOption;
Thanks :pray:
i tried with JSON Stringify, JSON Parse... Like in WEB,
You wants to set value in local storage so, don't need to set the value in useEffect hook. Just add in your saveOption function like
const saveOption = (item) => {
try {
let newValue = [...value, {name: item, id: Math.random()}]
AsyncStorage.setItem('option', newValue);
setValue(newValue);
} catch (e) {
console.log(e);
}
};
And make a getOption async function like
const getOption = async () => {
try {
const jsonValue = await AsyncStorage.getItem('option');
if (jsonValue) {
await setValue(jsonValue);
}
} catch (e) {
console.log(e);
}
};
Then render in JSX like
{value.map((item) => {
return <Text key={item.id}>{item.name}</Text>;
}