简体   繁体   中英

Update value of react native checkbox through firebase

I am trying to update the value of checkboxes (I am using the nativebase checkbox component) through firebase in my RN app. The value of the checkboxes is retrieved correctly from the database, but updating the values doesn't seem to work.

Here is the code:

const onButtonPress = (checkList, course) => {
    const { currentUser } = firebase.auth();

    firebase.database().ref(`/users/${currentUser.uid}/Year1/${course}`)
         .set({
                 checked: !checkList.Year1[course].checked
               });
};

and here is where it is called:

<CheckBox
   checked={checkList.Year1[course].checked}
   onPress={onButtonPress(checkList, course)}
 />

Here is the firebase database scheme

The data from firebase is retrieved as state from redux and mapped to the prop 'checkList'. I initialize all values of checklist to false until the request to fetch the data from firebase is complete (so the value of checkbox is never null to avoid getting an error), and so onPress just gets stuck in a loop calling itself as the value keeps changing (first as all values are set to false, then when the data has been initialized). I understand the problem but I am having trouble trying to fix it. My initial thought is onPress is only called when the user physically presses the checkbox not when the value is updated, so how can I change it so that onPress is called only when the user presses on the checkbox. Or is there another way to go by it? I have tried using other checkbox components available but I face the same problem with all of them. Any thoughts?

Here is the complete code of the component (removed styling and what not):

import React, { Component } from 'react';
import { Image, Text, View, ScrollView } from 'react-native';
import { connect } from 'react-redux';
import { List, ListItem, Right, Body, CheckBox } from 'native-base';
import firebase from 'firebase';
import Gradlist from '../Components/Gradlist';
import { courseFetch } from '../Actions/CourseActions';


const isEmpty = (obj) => {
  for (const prop in obj) {
   return false;
 }
 return true;
};

const onButtonPress = (checkList, course) => {
    const { currentUser } = firebase.auth();

    firebase.database().ref(`/users/${currentUser.uid}/Year1/${course}`)
         .set({
                 checked: !checkList.Year1[course].checked
               });
};

class Gradscreen extends Component {

  componentWillMount() {
    this.props.courseFetch();
  }


  render() {
    const { Year1, Year2, Year3, Year4 } = this.props.courses;
    let { checkList } = this.props;
    if (isEmpty(checkList)) {
        checkList = {
          Year1: {
            'COMM 101': {
          checked: false,
          grade: ''
        },
        'COMM 292': {
          checked: false,
          grade: '',
        },
        'CPSC 110': {
          checked: false,
          grade: ''
        },
        'CPSC 121': {
          checked: false,
          grade: ''
        },
        'ECON 101': {
          checked: false,
          grade: '',
        },
        'ECON 102': {
          checked: false,
          grade: '',
        },
        'ENGL 112': {
          checked: false,
          grade: '',
        },
        'MATH 104': {
          checked: false,
          grade: ''
        },
        'MATH 105': {
          checked: false,
          grade: '',
        }
      } };
    }


    return (
          <View>
            <ScrollView>
                  <Image
                        style={styles.pictureStyle}
                        source={require('../assets/bucsHeader.png')}
                  />
                  <Gradlist Header={'Year 1'}>
                    <List>
                       { Year1.map((course, i) => (
                         <ListItem icon key={i}>
                            <Body>
                              <Text> {course} </Text>
                            </Body>
                            <Right>
                              <CheckBox
                              checked={checkList.Year1[course].checked}
                              onPress={onButtonPress(checkList, course)}
                              />
                            </Right>
                         </ListItem>))
                     }
                    </List>
                  </Gradlist>
                </ScrollView>
            </View>
    );
  }
}

const mapStateToProps = state => ({
  courses: state.courses,
  checkList: state.checkList
});

export default connect(mapStateToProps, { courseFetch })(Gradscreen);

You're invoking the onButtonPress function everytime your render function is invoked. You need to pass the onPress prop a callback

To have the onPress attribute of your Checkbox perform correctly, change to the following

<Checkbox 
    checked={checkList.Year1[course].checked}
    onPress{() => onButtonPress(checkList, course)}
/>

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