简体   繁体   中英

Trying to store checkbox to asyncstorage

Im trying to make a react-native app in which if checkbox is true,it should be able to store the state in asyncstorage. I can't make it work, so hopefully someone helps me. I'am new to React Native so to asyncstorage and i have no idea

The code below is how far i've come trying to figure out on how to do it.

CODE

import React, { Component } from 'react';
import { CheckBox } from 'react-native-elements'
import { View, Button } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import Fontisto from 'react-native-vector-icons/Fontisto';


export default class Check extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: false,
    };
    this.getData();
  }

  storeData =  () => {
    this.setState(prevState => ({ checked: !prevState.checked }))
    if(this.state.checked == true){
      AsyncStorage.setItem("@storage_Key", JSON.stringify(this.state.checked));
    }
}

getData = () => {
  AsyncStorage.getItem("@storage_Key").then((value) => {
      if(value != null){
          this.setState({
              checked:true
          })
      }
  })
}

  render() {
    return (
      <View>
        <CheckBox
          checkedIcon={<Fontisto name='checkbox-active' size={15} color='#000' />}
          uncheckedIcon={<Fontisto name='checkbox-passive' size={15} color='#000' />}
          checked={this.state.checked}
          onPress={() => this.storeData()}
        />
      </View>


    );
  }
}

pressHandler code

const pressHandler = key => {
    console.log('Todos BEFORE delete');
    console.log(todos);

    const newTodos = todos.filter(todo => todo.key !== key);

    console.log('Todos AFTER delete');
    console.log(todos);

  };

submitHandler code

const submitHandler = text => {
    if (text.length === 0) return;

    const key = Math.random().toString();

    console.log('Todos BEFORE submit');
    console.log(todos);

    const newTodos = [{ text, key }, ...todos];

    console.log('Todos AFTER submit');
    console.log(todos);

  };

addList this makes so when the user click on add task it adds the task

export default function AddList({ submitHandler }) {

    const [text, setText] = useState('');

    const changeHandler = (val) => {
        setText(val);
    }
    const onSubmit = useCallback(() => {
        if (submitHandler) submitHandler(text)
        setText("")
    }, [text])

    return (
        <View style={styles.container}>
            <View style={styles.wrapper}>
                <TextInput
                    style={styles.input}
                    placeholder='What Tododay?'
                    onChangeText={changeHandler}
                    value={text}

                />
                <View>
                    <Feather type='Feather' style={styles.icon} onPress={onSubmit} name='plus-circle' size={40} color='#000' />
                </View>
            </View>
        </View>
    );
} 

Try the following:

storeData = async () => {
  const state = this.state.checked
  this.setState({ state: true })
  try {
    await AsyncStorage.setItem('@storage_Key', state)
  }
  catch(err) {
    console.log(err)
  }
}

I'm taking the value of the state in the constant and if it's true it does that process, you can pass more logic using the if and else

async savePlaces() {
  var places = this.state.places
  await AsyncStorage.setItem('places', JSON.stringify(places));
}

Here above is a code where I store locations in my state

async getPlaces() {
  var NewArray = await AsyncStorage.getItem('places');
  var places = JSON.parse(NewArray)
  this.setState({ places: places })
}

And up here I call them

Good luck

You can use Asynstorage from react-native which is easy to use, you can do something like this:

import React, { Component } from 'react';
import { CheckBox } from 'react-native-elements'
import { AsyncStorage, View, Button } from 'react-native';


export default class Check extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: false,
    };
    this.getData();
  }

  storeData =  () => {
      this.setState(prevState => ({ checked: !prevState.checked }))
      if(this.state.checked == true){
        AsyncStorage.setItem("@storage_Key", JSON.stringify(this.state.checked));

      }
  }

  getData = () => {
    AsyncStorage.getItem("@storage_Key").then((value) => {
        if(value != null){
            this.setState({
                checked:true
            })
        }
    })
  }

  render() {
    return (
      <View style={{flex:1,marginTop:100}}>
      <CheckBox
  center
  title='Click Here'
  checkedIcon='dot-circle-o'
  uncheckedIcon='circle-o'
  checked={this.state.checked}
  onPress={() => this.storeData()}
/>
<Button title="GetData" onPress={this.getData}></Button>
      </View>


    );
  }
}

on consoling the value you will get value is {"state":true}

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM