-
Type: Task
-
Resolution: Unresolved
-
Priority: Major - P3
-
None
-
Affects Version/s: None
-
Component/s: None
-
2 - S (<= 1 week)
-
2345
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).