0

I got my JSON data API and wanted it to populate to the checkbox in the flatlist while the user is able to change the checkbox and send it back to the API call.

The problem is I am unable to create a working checkbox in the flatList using a functional component.

My studentAtt is either 0 or 1 from the database while checked means present (1), unchecked means absent(0).

This is how many data - classAtt looks like [{"studentID":"123","studentName":"User 1","studentAtt":0},{"studentID":"456","studentName":"User 2","studentAtt":0}]

import {CheckBox} from "react-native-elements";
const MarkAttendanceScreen = (props) => {
    const dispatch = useDispatch();
    const classAtt = useSelector(state => state.attendance.attendanceClass);
    const [attInfo,setAttInfo] = useState(JSON.stringify(classAtt));

    //fetch attendance
    const loadClassAtt = useCallback(async () => {
        let tempDate = new Date();
        let dateToDB = moment(tempDate).format('YYYY-MM-DD');
        try {
            await dispatch(attendanceActions.fetchClassAttendance(dateToDB));

        } catch (err) {
            setError(err.message);
        }

    }, [dispatch]);

    const updateAttendance = (id) =>{
        let temp = attInfo.map((info) => {
            if (id === info.studentID) {
                return { ...info, studentAtt: !info.studentAtt };
            }
            return info;
        });
        setAttInfo(temp);
    }

return(
   <FlatList
      onRefresh={loadClassAtt}
      refreshing={isRefreshing}
      data={classAtt}
      showsVerticalScrollIndicator={false}
      keyExtractor={(item, index) => index.toString()}
      extraData={classAtt}
      renderItem={({ item, index })=>(
            <AttendanceSign
                studentName={item.studentName}
                studentID={item.studentID}
            >

                  <CheckBox
                      checked={item.studentAtt}
                      onPress={() => updateAttendance(item.studentID)}
                   />


            </AttendanceSign>
          )}
  />
);

}

Hope to seek help from the experts on how to implement a working checkbox in flatlist RN

2
  • What exactly is not working here? Commented Mar 5, 2022 at 21:10
  • It says attInfo.map((info) , undefined is not an object the checkbox cannot be checked too Commented Mar 6, 2022 at 4:02

1 Answer 1

2

I am not sure why are you doing the JSON.stringify(classAtt)? anyways i have created a simple snack example of checkbox using flatlist for you :- https://snack.expo.dev/@arjunshukla97/a53a12

P.s:- This is just one of the many ways of implementing checkbox using flatlist. :)

Sign up to request clarification or add additional context in comments.

5 Comments

Hi, really thanks for that. As the API data is in Object format hence need to stringify it into JSON aray. Anyway, it works for me really thanks for the help. Another question that I would like to ask. How should i pass all the updates to an array and update it to the API call with a submit button. It means the user can check as many boxes as he/she wants, the changes will only commit to the db after the submit button is clicked.
Since you're storing the data in a reducer, then creating a local state and updating the value of studentAtt key on click of checkbox, you can simply update the state of reducer and send a post request to backend on click of a button. So, In case user doesn't press on submit button the global state (reducer) wouldn't get updated and if the user will come back to the screen it will again show the default status of checkbox.
One more question the setRefresh(!refresh) will let the list keeps on load/spinning after I checked the box. Why it is so yea?
setRefresh(!refresh); is just to make the component re-render, in order to reflect the changes made in the data to UI. What do you exactly mean by load/spinning, i am not sure. Some code and video for reference might be helpful.
I see understood. For my case, when i click the checkbox, the spinner will appear & keep spinning. It will stop until I clicked another checkbox.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.