2

I have a listing screen where I list some data, and another one for data input. When the listing screen opens, I fetch the data from the local database and put them in the state. And also set up schema change listener for newly inserted data. From this screen I can navigate to the form screen where I save the form data to database and go back to the list screen. When form data is submitted, I want the schema change listener to fire up and push the inserted object to the state in the listing screen.

I can receive the inserted object in the listener but when I push it to the state previous data is empty.

FarmerListScreen.js

const FarmerListScreen = () => {
    const [farmers, setFarmers] = useState([]);

    useEffect(() => {
        const fetchedFarmers = db.getFarmers();
        
        setFarmers(fetchedFarmers);
    }, []);

    useEffect(() => {
        const farmersSchema = db.realm.objects('Farmer');
        function onFarmersChange(farmersSchema, changes) {
            changes.insertions.forEach(index => {
                const insertedFarmer = farmersSchema[index];
                setFarmers([insertedFarmer, ...farmers]); // farmers is empty array
            });
        }
        try {
            farmersSchema.addListener(onFarmersChange);
        } catch (error) {
            console.error(
                `An exception was thrown within the change listener: ${error}`,
            );
        }

        return () => {
            farmersSchema.removeListener(onFarmersChange);
        };
    }, []);

    ...

};

FormScreen.js

const FormScreen = ({navigation}) => {
    ...

    const handleSubmitButtonPress = async () => {
        const data = {
            identificationNumber,
            firstName,
            lastName,
            fathersName,
            dob: dayjs(selectedDobDate).format('YYYY-MM-DD'),
            phoneNumber,
            company: {companyName: selectedCompany?.value},
            village: {villageName: selectedVillage?.value},
        };

        db.addFarmer(data);
        
        navigation.goBack();
    };

    return (
        ...
    );
};

By the time when I push the insertedFarmer to the farmers state, the farmers state has only one item, which is the insertedFarmer. What am I doing wrong?

  • Did you do some basic troubleshooting by adding a breakpoint and stepping through the code line by line, inspecting the vars and code execution until you spot something unexpected? If so, please indicate which line is not working as intended. Also, why are you using arrays instead of Realm Collection objects? If you did that then when a change event fires, just reload the UI and the new data will be there. – Jay Apr 12 '23 at 17:42

0 Answers0