WatermelonDB icon indicating copy to clipboard operation
WatermelonDB copied to clipboard

"withObservables()" method still not reactive, try with ".subscribe()" method but you can't replace an Object with "setState()" in function component

Open VEmpink opened this issue 6 years ago • 6 comments

"@nozbe/watermelondb": "^0.20.0",
"@nozbe/with-observables": "^1.0.6",
"react-native": "0.63.2",

I am using useObservables Hook an alternative "withObservables()" method

BUT

You can't setState() an Object directly like setState(obj) see useState Hook for more detail

my Hook.js

import React, {useState, useEffect} from 'react';
import utils from '../utils';

const useObservable = observable => {
  const [state, setState] = useState(null);

  useEffect(() => {
    const subscription = observable.subscribe(newValues => {



      // You CAN'T "setState()" like this it WON'T re-render the component
      setState(newValues);



      // You MUST using Object destructing when "setState()" an Object in Functional Component,
      // BUT also the problem when you "setState()" like this and
      // when trying to display the value from the database
      // I have to code like "props.user._raw.some_value",
      // it's mean why I must adding "_raw" property every to get a value
      // from the database instead of "props.user.some_value"
      // BEFORE "setState()" with Object destructing it's just fine
      // BUT the component won't re-render.
      // Any idea?
      setState(prevState => ({...prevState, ...newValues}));
    });
    return () => subscription.unsubscribe();
  }, []);

  return state;
};

export {useObservable};

VEmpink avatar Oct 26 '20 16:10 VEmpink

   // You MUST using Object destructing when "setState()" an Object in Functional Component,
      // BUT also the problem when you "setState()" like this and
      // when trying to display the value from the database
      // I have to code like "props.user._raw.some_value",
      // it's mean why I must adding "_raw" property every to get a value
      // from the database instead of "props.user.some_value"
      // BEFORE "setState()" with Object destructing it's just fine
      // BUT the component won't re-render.
      // Any idea?

you seem to have some misconceptions about how React hooks, Rx and/or JavaScript ... operator work. setState via hooks won't re-render if you pass it an identical value, and if you observe a Watermelon record, for example, every emission has the same identity. But if you ...object, where object is not a POJSO but an instance of a Model, naturally you're destroying all methods, getters, etc. That's why you find yourself needing to use _raw (which is preserved).

I recommend that you DO NOT use the useObservable hook as pasted in the post. It has many unsolved flaws, and only "works" if you have good understanding of how it works. Use withObservables, which might have an uglier syntax, but just works.

If you must, you need to force an update from hook somehow. Here's an example of a "force update" hook:

const increment = x => x + 1
export default function useForceUpdate(): () => void {
  const [, forceUpdate] = React.useReducer(increment, 0)
  return forceUpdate
}

radex avatar Oct 27 '20 14:10 radex

@radex I've been trying with withObservables method and it's successfully displaying the data BUT it's not reactive :(

MyTestScreen.jsx

import React, {useEffect, useState} from 'react';
import {Button, Layout} from '@ui-kitten/components';
import WATERMELON from '../models';
import util from '../utils';
import {View} from 'react-native';
import withObservables from '@nozbe/with-observables';
import {Text} from '../components/Helper';

const enhance = withObservables(['user'], props => ({
  user: props.user,
}));

const UserBasicInfo = enhance(props => (
  <>
    <Text>{props.user.name}</Text>
  </>
));

const InitialLoading = props => {
  const [user, setUser] = useState(null);
  useEffect(() => {
    (async () => {
      await WATERMELON.action(async () => {
        const user_collection = WATERMELON.collections.get('user');
        const fetch_userdata = await user_collection.query().fetch();

        /**
         * I don't know why can just "fetch_userdata[0]" instead of
         * "[fetch_userdata[0]]"
         *
         * I just wanna get the first data but without Id or ".find() method" :(
         */
        setUser([fetch_userdata[0]]);
      });
    })();
  }, []);

  return (
    <Layout>
      <View>
        <Text>Hello World!</Text>

        {user !== null && <UserBasicInfo user={user} />}

        <Button
          onPress={async () => {
            // Not reactive the component :(
            await WATERMELON.action(async () => {
              const user_collection = WATERMELON.collections.get('user');
              const fetch_userdata = await user_collection.query().fetch();
              await fetch_userdata[0].update(user => {
                user.name = 'Yay!';
              });
            });
          }}
        >
          Press It
        </Button>
      </View>
    </Layout>
  );
};

export default InitialLoading;

VEmpink avatar Oct 27 '20 14:10 VEmpink

         * I don't know why can just "fetch_userdata[0]" instead of
         * "[fetch_userdata[0]]"

As I explained, you can't pass an identical object to hook state update and expect it to reload. You're wrapping it an array

then passing that array to a component:

 {user !== null && <UserBasicInfo user={user} />}

an array of a User is not observable. You need to pass the User.

radex avatar Oct 27 '20 15:10 radex

@radex Sorry, I don't understand

You need to pass the User.

VEmpink avatar Oct 27 '20 15:10 VEmpink

Your user is an array of users. A array itself it's not observable.

change setUser([fetchUser[0]]) to setUser(fetchUser[0])

This way you'll have a observable.

luk3skyw4lker avatar Nov 24 '20 11:11 luk3skyw4lker

It seems when I am using this version"@nozbe/with-observables": "^1.0.7", my Issue here is gone but I facing a New Issue that is not a big problem for me.

Here the Example of how I use withObservables()

import React, {useEffect, useState} from 'react';
import {View} from 'react-native';
import {Contrainer} from '../components/helper';
import FolderShowcase from '../components/Home/FolderShowcase';
import db from '../models';
import withObservables from '@nozbe/with-observables';

const enhance = withObservables(['data'], ({data}) => ({
  data,
}));

const EnhancedFolderShowcase = enhance(FolderShowcase);

/**
 * In here I wanna displaying a data as a List
 */
const Home = props => {
  const [folders, setFolders] = useState(null);

  useEffect(() => {
    (async () => {
      const folderCollections = db.collections.get('folders');

      const listFolder = folderCollections.query();
      setFolders(listFolder);
    })();
  }, []);

  return (
    <Contrainer>
      {folders && <EnhancedFolderShowcase data={folders} />}
    </Contrainer>
  );
};

export default Home;

FolderShowcase.jsx

import React from 'react';
import {FlatList} from 'react-native';
import {Text} from '../helper';

const FolderShowcase = props => {
  return (
    <FlatList
      data={props.data}
      renderItem={items => {
        const folder = items.item;

        return (
          <>
            {folder && <Text>{folder.name}</Text>}
          </>
        );
      }}
    />
  );
};

export default FolderShowcase;

VEmpink avatar Nov 27 '20 22:11 VEmpink