Search code examples
javascriptreactjsreact-nativeradio-buttonasyncstorage

How to store chosen radio button value in a AsyncStorage in React Native?


I would like to store/save the users chosen radio button value in a AsyncStorage. How is this achieved? I am retrieving the radio button values from another file and assigning them to the labels. These are the structures of my radio buttons:

import RadioButtonRN from 'radio-buttons-react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

const Radio = () => {
  const label1 = Questions[2].answers[0].answer;
  const label2 = Questions[2].answers[1].answer;
  const label3 = Questions[2].answers[2].answer;

  const data = [
    {
      label: label1,
    },
    {
      label: label2,
    },
    {
      label: label3,
    },
  ];

  return (
    <RadioButtonRN
      data={data}
      selectedBtn={(e) => console.log(e)}
      box={false}
      circleSize={14}
      activeColor={'#6175CF'}
      style={styles.radio}
    />
  );
};

export default Radio;

Solution

  • You can directly use javascript's localStorage to store and fetch values from session. setSelectedRadioBtn sets the value in storage by name radioBtn and getSelectedRadioBtn gets the value stored in storage

    setSelectedRadioBtn = (selectedBtn) => localStorage.setItem('radioBtn', selectedBtn);
    
    getSelectedRadioBtn = () => console.log(localStorage.getItem('radioBtn'));
    
    return (
            <RadioButtonRN
              data={data}
              selectedBtn={(e) => setSelectedRadioBtn(e)}
              box={false}
              circleSize={14}
              activeColor={'#6175CF'}
              style={styles.radio}
            />
      )
    }