Save checkbox status in Asyncstorage

Asked

Viewed 206 times

1

I have a check box which by default is marked as true (marked), but, I want to dynamically save an option when the user changes this box to false (or, cancel). As I will not have bank interaction yet, I searched about and decided to do it with Asyncstorage. However, I was unsuccessful after seeing some examples. My code starts with:

state = {
    bt_contact: true
}

storeCheckBoxStatus = async () => {

        try {
            await AsyncStorage.setItem('@storage_Key', this.state.bt_contact)
            console.info(AsyncStorage)
        } catch (e) {
            console.info(e);
        }
    }

    getCheckBoxStatus = async () => {
        try {
            const value = await AsyncStorage.getItem('@storage_Key')
            console.info(AsyncStorage)
            console.info(value)
            if (!value != null) {
                this.setState.bt_contact({bt_contact: (value).bt_contact})
            }
        } catch (e) {
            console.info(e);
        }
    }

    checkBoxTest() {
        this.setState({
            bt_contact: !this.state.bt_contact
        })

        if (!this.state.bt_contact != true) {

            Alert.alert(
                I18n.t('Confirm_cancel_data_sharing'),
                I18n.t('Message_alert_data_sharing'),
                [

                    {
                        text: I18n.t('Cancel'),
                        onPress: () => this.setState({
                            bt_contact: true
                        })

                    },
                    {
                        text: 'OK',
                        onPress: () => this.storeCheckBoxStatus
                    },
                ],
                { cancelable: false }
            )
        }
    }

The first function should read the user record when unchecking the box or not. The second is to render with the value changed for the last time or come as marked by default. And the latter is only interaction with Alert. That when he cancels, he reschedules and when the ok, will give sequence to be able to save in Torage.

I need you to be safe in Asyncstorage and that I can access, so if you need to send to the bank in the future, you can consult. But from the beginning, I would just like that once you close the phone, you can leave the last option saved. If you clear, reopen unchecked. Anyone can help?

Chunk that rescan the checkbox:

<Text style={[styles.bottomContainerText, { color: themes[theme].auxiliaryText }]}>
    <CheckBox style={{
            height: 10,
            widht: 10,
        }}
        value={this.state.bt_contact}
        onValueChange={() => this.checkBoxTest()}
    />
    {I18n.t('Data_sharing')}
</Text>
  • A tip: put more details on the questions.

1 answer

1

@Wanderson Bueno, the easiest way to solve your problem is by creating a hook that will take the value of the checkbox, identify whenever there is change in it and store in asyncStorage, after that, we need to take the amount that is in Async Storage and add it to the Checkbox whenever the App opens.

For this, we will create a component and put the Checkbox inside.

export default function App() {
  const [isSelected, setSelection] = useState(false);

  return (
    <View>
        <CheckBox
          value={isSelected}
          onValueChange={setSelection}
        />
    </View>
  );
}

After the creation of Checkbox, we need to create two functions to manage Async Storage, one to add and one to remove the value, always referencing by key, which in this case is @checkbox:

const saveValue = async (value) => {
    try {
      const jsonValue = JSON.stringify(value);
      await AsyncStorage.setItem('@checkBox', jsonValue)
    } catch (e) {
      // saving error
    }
  };

  const getValue = async () => {
    try {
      const jsonValue = await AsyncStorage.getItem('@checkBox');
      return jsonValue != null ? JSON.parse(jsonValue) : null;
    } catch(e) {
      // error reading value
    }
  };

Next we just need to create a hook to identify if the Checkbox value is changing, then move on to the function we created to add the value to Async Storage:

  useEffect(
    () => {
      saveValue(isSelected)
    },
    [isSelected],
  );

Finally, we only need to identify when that Screen will render and check if there is any value in Async Storage, if Hover, we add it to the Checkbox:


// Para identificar quando o componente é montado podemos usar o useEffect passando um array vazio, como mostrado no exemplo abaixo.

useEffect( async () => {
    let checkBoxValue = await getValue();
    setSelection(checkBoxValue)
  }, []);

Complete code:

import React, { useState, useEffect } from 'react';
import { StyleSheet, View, CheckBox } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';

export default function App() {
  const [isSelected, setSelection] = useState(false);

  const saveValue = async (value) => {
    try {
      const jsonValue = JSON.stringify(value);
      await AsyncStorage.setItem('@checkBox', jsonValue)
    } catch (e) {
      // saving error
    }
  };

  const getValue = async () => {
    try {
      const jsonValue = await AsyncStorage.getItem('@checkBox');
      return jsonValue != null ? JSON.parse(jsonValue) : null;
    } catch(e) {
      // error reading value
    }
  };

  useEffect( async () => {
    let checkBoxValue = await getValue();
    setSelection(checkBoxValue)
  }, []);

  useEffect(
    () => {
      saveValue(isSelected)
    },
    [isSelected],
  );

  return (
    <View style={styles.container}>
        <CheckBox
          value={isSelected}
          onValueChange={setSelection}
        />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

I hope I’ve helped.

  • I’m analyzing. I missed the section that I rescan the checkbox. I just edited.

  • In that case I couldn’t use Alert to define the actions of Cancel and Ok?

  • Could, would have to create a change Handler to the value of Checkbox.

  • failed using hook. Is it necessary to use JSON.parse? Of the examples I saw to try to save and then render with the last option checked, almost all used without, as posted.

  • JSON.parse is not required, it is only necessary when an Asyncstorage Object is returned, but I always use it by default. I will update the reply with Handler displaying an Alert to confirm the Checkbox value change.

  • Fair. I get it now!

  • I couldn’t, but I understood the concept, I’ll try here.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.