0

I am using WatermelonDB in my RN app. I am trying to display a button if WatermelonDB has unsynced changes. WatermelonDB has a function called hasUnsyncedChanges that returns a boolean. I can get the function to console.log true/false. But unsure how to use this outside of the async function.

async function checkUnsyncedChanges() {
    return await hasUnsyncedChanges({database});
}

  (async () => {
    console.log(await checkUnsyncedChanges());})();

I am new to React Native and have had good luck researching other issues with WatermelonDB but running into a wall in how to get this working.

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
doobe01
  • 1
  • 2

1 Answers1

0

I figured it out. Code below for anyone having similar difficulties.

import React, {useState, useEffect, useContext} from 'react';
import {View, Text, Button} from 'react-native';
import {hasUnsyncedChanges} from '@nozbe/watermelondb/sync';
import {database} from '../database/db';
import {sync} from '../components/watermelonSync';
import {AuthContext} from '../AuthProvider';

const SyncButton = () => {
  const {user} = useContext(AuthContext);
  const [showButton, setShowButton] = useState(false);

  useEffect(() => {
    const checkUnsyncedChanges = async () => {
      const unsyncedChanges = await hasUnsyncedChanges({database});
      setShowButton(unsyncedChanges);
    };

    checkUnsyncedChanges();
  }, []);

  return (
    <View>
      {showButton && (
        <Button title="Sync Changes" onPress={() => sync(user.token)} />
      )}
    </View>
  );
};

export default SyncButton;
Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
doobe01
  • 1
  • 2