Uploaded image for project: 'Realm JavaScript SDK'
  1. Realm JavaScript SDK
  2. RJS-447

Update example apps to show Realm integrated with the latest React Native APIs (React Hooks, FlatList, ...)

    • Type: Icon: Task Task
    • Resolution: Unresolved
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: None

      I created this in stackoverflow: https://stackoverflow.com/questions/55741282/flatlist-not-updating-with-react-hooks-and-realm

      Basically, I created a React Hook to access Realm:

      /* @flow */
      
      import { useState, useEffect } from 'react';
      
      export default function useRealmResultsHook(query, args): Array {
        const [data, setData] = useState(args ? query(...args) : query());
      
        useEffect(
          () => {
            function handleChange(newData) {
              setData(newData);
            }
      
            const dataQuery = args ? query(...args) : query();
            dataQuery.addListener(handleChange);
            return () => {
              dataQuery.removeAllListeners();
            };
          },
          // eslint-disable-next-line react-hooks/exhaustive-deps
          [query, ...args]
        );
      
        return data;
      }
      

      And then I use it:

      const MyComponent = (props: Props) => {
        const data = useRealmResultsHook(getDataByType, [props.type]);
      
        return (
          <View>
            <FlatList
              data={data}
              keyExtractor={keyExtractor}
              renderItem={renderItem}
            />
          </View>
        );
      };
      

      Long story short, FlatList does not update because it looks like {{data === newData }} (reference) as Realm mutates the result (not creating a new copy).

      Like this works:

      setData([...newData]);
      

      But doing so I get a plain JS array, not Realm Results anymore. What is the best way to do this? How to better clone Realm Results? I am afraid that [...newData] might be quite inefficient for big amounts of data.

      TBH, it looks to be nothing about the hook but just Realm

      • FlatList (FlatList expects always a new array reference in order to update, not a mutated on).

            Assignee:
            Unassigned Unassigned
            Reporter:
            unitosyncbot Unito Sync Bot
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated: