I have this simple react native app that on button click it redirects user to a page. I’m saving data in a cache so that if user clicks the store button it stores data and after refresh it sets store data. However, I would like to implement this logic on a single button, not on 2 different buttons as it is now. Can someone explain me how could I achieve this?
JavaScript
x
39
39
1
export const App = () => {
2
const [showFirstWeb, setFirstWeb] = useState(false);
3
4
const getData = async () => {
5
try {
6
const jsonValue = await AsyncStorage.getItem("@web_Key");
7
return setFirstWeb(JSON.parse(jsonValue));
8
} catch (e) {
9
console.log("error", e);
10
}
11
};
12
13
useEffect(() => getData, []);
14
15
const storeData = async () => {
16
try {
17
const jsonValue = JSON.stringify(showFirstWeb);
18
await AsyncStorage.setItem("@web_Key", jsonValue);
19
} catch (e) {
20
console.log("error", e);
21
}
22
};
23
24
return (
25
<View>
26
<View style={styles.buttonStyle}>
27
<Button onPress={setFirstWeb(!showFirstWeb)}/>
28
<Button onPress={storeData} title="store"/>
29
<View>
30
{showFirstWeb && <MyWebComponent uri="https://www.google.com/" />}
31
</View>
32
</View>
33
);
34
};
35
36
const MyWebComponent = (uri) => {
37
return <WebView source={uri} />;
38
};```
39
Advertisement
Answer
JavaScript
1
39
39
1
export const App = () => {
2
const [showFirstWeb, setFirstWeb] = useState(false);
3
4
const getData = async () => {
5
try {
6
const jsonValue = await AsyncStorage.getItem("@web_Key");
7
return setFirstWeb(JSON.parse(jsonValue));
8
} catch (e) {
9
console.log("error", e);
10
}
11
};
12
13
// you forgot to call the function here
14
useEffect(() => getData(), []);
15
16
const storeData = async () => {
17
try {
18
// get the new value
19
const newShowFirstWeb = !showFirstWeb
20
// use the new value
21
setFirstWeb(newShowFirstWeb)
22
const jsonValue = JSON.stringify(newShowFirstWeb );
23
await AsyncStorage.setItem("@web_Key", jsonValue);
24
} catch (e) {
25
console.log("error", e);
26
}
27
};
28
29
return (
30
<View>
31
<View style={styles.buttonStyle}>
32
<Button onPress={storeData} title="store"/>
33
<View>
34
{showFirstWeb && <MyWebComponent uri="https://www.google.com/" />}
35
</View>
36
</View>
37
);
38
};
39