Search code examples
javascriptfirebasereact-nativeexpoasyncstorage

How to save State in React Native to Firebase


I am creating an app that allows a user to select multiple items from a Flatlist and the state changes once selected. However when I move away from that screen, all the selected items go back to the unselected state. How can use Firebase to save that state so it doesn't revert when I leave the screen? I am also open to alternative solutions to this issue.

Thank you for your time.

export default function StoreCatalogue({ navigation }) {

    const { data, status } = useQuery('products', fetchProducts)

    const [catalogueArray, setCatalogueArray] = useState([])
    const [isSelected, setIsSelected] = useState([])
    const [addCompare, setAddCompare] = useState(false)

      const storeToDB = async (item) => {
        if (!addCompare) {
            await db.collection('users').doc(auth.currentUser.uid).collection('myProducts').doc(item.storeName + item.genName).set({
                product_id: item.id,
                product_genName: item.genName
            })
        } else {

            await db.collection('users').doc(auth.currentUser.uid).collection('myProducts').doc(item.storeName + item.genName).delete()
        }
    }


    const clickHandler = async (item) => {

        setAddCompare(
            addCompare ? false : true
        )

        if (isSelected.indexOf(item) > -1) {
            let array = isSelected.filter(indexObj => {
                if (indexObj == item) {
                    return false
                }
                return true
            })
            setIsSelected(array)
        } else {
            setIsSelected([
                ...isSelected, item
            ])
        }
    }

    return (
        <View style={styles.container}>

            <FlatList
                extraData={isSelected}
                keyExtractor={(item) => item.id}
                data={catalogueArray}
                renderItem={({ item }) => (
                    <TouchableOpacity style={styles.btn} onPress={() => { storeToDB(item); clickHandler(item) }}>
                        <MaterialCommunityIcons name='plus-circle-outline' size={24} color={isSelected.indexOf(item) > -1 ? 'grey' : 'green'} />
                           <View style={{ position: 'absolute', bottom: 3 }}>
                              <Text style={{ fontSize: 10, textAlign: 'center', color: isSelected.indexOf(item) > -1 ? 'grey' : 'green' }}>{isSelected.indexOf(item) > -1 ? 'item \nAdded' : 'Add to\n Compare '}</Text>
                           </View>
                    </TouchableOpacity>
               )}
            />
        </View>
    )
}


Solution

  • The problem is when you leave a screen the state gets reset to original, you can use Redux to store the state separately and on an event store the information on firebase once.

    Firebase can be costly for this operation since every read and write will be chargeable.