I'm using React-Native and Expo.
I've got a situation where I have an image flatlist, populated from an SQLite database. I also have a 2nd flatlist populated from a different table in the database. The 2nd flatlist shows Checkboxes and these checkboxes add/remove entries into a bridge table in the database, as seen below:
Table 'images':
file_name |
---|
file1.jpg |
file2.jpg |
Table 'types':
type |
---|
type_a |
type_b |
Table 'images_types_bridge':
file_name | type |
---|---|
file1.jpg | type_a |
file2.jpg | type_a |
file2.jpg | type_b |
The image flatlist shows all the images from 'images'. When at least one image is selected by the user (tapping selects the image), a component appears at the bottom of the screen containing options for the user, e.g. the ability to delete the image. It also contains a flatlist of checkboxes of all the types from the 'types' table. When a user checks/unchecks one of these boxes, the 'images_types_bridge' table is updated accordingly. This all works fine.
The issue comes in populating the checkboxes when an image is initially selected. I originally thought it best to have each flatlist item manage its own state, like the following:
MyCheckBox.js:
import { useState } from 'react';
import CheckBox from 'expo-checkbox';
const MyCheckBox = props => {
const [isChecked, setIsChecked] = useState(false);
return (
<CheckBox
value={isChecked}
onValueChange={(newValue) => { setIsChecked(newValue) }} />
);
};
export default MyCheckBox;
And the relevant code in ImagesScreen.js:
const [images, setImages] = useState([]);
const [types, setTypes] = useState([]);
const [imagesExtra, setImagesExtra] = useState(true);
// selectedImages is an array of image Flatlist indices to indicate which images are currently selected.
const [selectedImages, setSelectedImages] = useState([]);
...
<Flatlist
/*
images = {
"file_name": "sample_file_name.jpg",
"types": ["type_a", "type_b", etc.]
*/
data={images}
// extraData is used for updating the displayed flatlist such as when the user selects an image
extraData={imagesExtra}
keyExtractor={item => item.file_name}
renderItem={renderImageItem}
/>
...
// This flatlist is only visible if an image is selected and the status of each of the checkboxes in it should reflect the selected image's 'types' array in the item object.
<Flatlist
data={types}
keyExtractor={item => item.type}
renderItem={renderTypeItem}
/>
...
function renderTypeItem({ item }) {
return (
<MyCheckBox
onValueChange={onCheckChange} // onCheckChange updates the database
item={item}
/>
);
}
How can I set the values of the checkboxes (true/false) when a user selects an image (I only need to worry about the first image selected) based on what is contained in the image flatlist item object's "types" array?
Aucun commentaire:
Enregistrer un commentaire