How can I conserve data when I change screen in React-Native?

AsteroidSnowsuit :

In my code, I have a page that shows a list of elements retrieved from a database. However, I also added a page that allows the user to select several filters.

I have two problems:

  1. I must save the data after I get away from the page (it musts stay there)
  2. I must transfer the data back to the list of elements.

I thought that by giving the filter screen a var from the previous screen, it would save the data in there, but it doesn't seem to work.

Do you have any indication about what I should do ?

import React from 'react'
import { SafeAreaView, View, Text } from 'react-native'
import {generalStyles} from '@gym-app/styles/general'
import { useTranslation } from 'react-i18next'
import { TouchableOpacity } from 'react-native-gesture-handler';

export default function ExerciseSelectorScreen({navigation}) {

    const {t} = useTranslation();
    var filterProps = {};

    return (
        <SafeAreaView style={generalStyles.contentContainer}>
            <View style={[generalStyles.contentContainer]}>
                <Text>{JSON.stringify(filterProps)}</Text>
                <View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center'}}>
                    <Text style={generalStyles.title}>{ t('exercise.exercises') }</Text>
                    <TouchableOpacity onPress={() => {navigation.navigate('Exercises Filter', {filterProps: filterProps})}} style={{padding: 10, backgroundColor: '#ffb623'}}>
                        <Text style={{fontSize: 20, fontWeight: 'bold'}}>{t('general.filters').toUpperCase()}</Text>
                    </TouchableOpacity>
                </View>
            </View>        
        </SafeAreaView>
    )
}

import React, { useState, useEffect } from 'react'
import { View, SafeAreaView, Text, ScrollView, StyleSheet } from 'react-native'
import {generalStyles} from '@gym-app/styles/general'
import { useTranslation } from 'react-i18next'
import persistent from '@gym-app/database/persistent'
import tdb from '@gym-app/translation/object'
import CheckboxGroup from '../../components/workout/exercises/filters/CheckboxGroup'
import { useRoute } from '@react-navigation/native';

export default function ExercisesFilterScreen() {

    const {t} = useTranslation();
    const route = useRoute();
    var filterProps = route.params.filterProps;
    const [equipments, setEquipments] = useState({});
    const [selectedEquipments, setSelectedEquipments] = useState({});
    const [order, setOrder] = useState('');
    const [machine, setMachine] = useState('yes');

    useEffect(()=> {
        if (Object.values(equipments).length == 0) {
            persistent.transaction(tx => {
            tx.executeSql(
                "SELECT * FROM equipment",
                [],
                    (t, s) => {
                        var transEquip = {};
                        Object.values(s.rows._array).map((equipment) => {
                            transEquip[equipment.id] = tdb(equipment, 'name')
                        })
                        setEquipments(transEquip);
                    },
                    (t, e) => {
                        console.log(e);
                    }
                );
            });
        }
    },[equipments])

    useEffect(() => {
        filterProps.selectedEquipments = selectedEquipments;
        filterProps.order = order;
        filterProps.machine = machine;
    })

    return (
        <SafeAreaView style={{flex: 1}}>
            <ScrollView style={[generalStyles.contentContainer, {flex: 1, backgroundColor: '#ffb623'}]}>
                <Text style={{fontSize: 30, fontWeight: 'bold', color: '#ffffff', textAlign: 'center'}}>{t('general.filters').toUpperCase()}</Text>
                <View style={{marginTop: 10}}>
                <CheckboxGroup
                    title={t('exercise.availableEquipment')}
                    selected={selectedEquipments}
                    select={setSelectedEquipments}
                    multi={true}
                    options={
                        equipments
                    }
                />
                <CheckboxGroup
                    title={t('exercise.order')}
                    selected={order}
                    select={setOrder}
                    multi={false}
                    options={
                        {
                            "asc": t('exercise.easyToHard'),
                            "desc": t('exercise.hardToEasy'),
                        }
                    }
                    undefined={'allow'}
                />
                <CheckboxGroup
                    title={t('exercise.machines')}
                    selected={machine}
                    select={setMachine}
                    multi={false}
                    options={
                        {
                            "yes": t('exercise.machine.yes'),
                            "no": t('exercise.machine.no'),
                            "only": t('exercise.machine.only')
                        }
                    }
                />
                </View>
            </ScrollView>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    optionTitle: {
        marginBottom: 6, 
        fontSize: 24, 
        fontWeight: 'bold', 
        color: '#ffffff', 
        textAlign: 'left'
    }
})
Lewa Bammy Stephen :

The global scope in React Native is variable global. Such as global.foo = foo, then you can use global.foo anywhere.

But do not abuse it! In my opinion, global scope may used to store the global config or something like that. Share variables between different views, as your description, you can choose many other solutions(use redux,flux or store them in a higher component), global scope is not a good choice.

A good practice to define global variable is to use a js file. For example global.js

global.foo = foo;
global.bar = bar;

Then, to make sure it is executed when project initialized. For example, import the file in index.js:

import './global.js'
// other code

Now, you can use the global variable anywhere, and don't need to import global.js in each file. Try not to modify them!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=34463&siteId=1