Nozbe / WatermelonDB

🍉 Reactive & asynchronous database for powerful React and React Native apps ⚡️
https://watermelondb.dev
MIT License
10.49k stars 589 forks source link

Adding `observeCount()` to `useObservables` on a child component causes React `setState` to be called before the component is mounted #1443

Open dsemelianov opened 1 year ago

dsemelianov commented 1 year ago

I'm new to WatermelonDB and am just getting it set up in my project.

I have a parent component called "UnsubscribeTab" which uses useObservables to listen to an observable, like so:

Screen Shot 2022-11-27 at 1 30 02 AM

As you can see, that parent component renders a child component called "EnhancedEmailListItem". The definition of that child component is as follows:

Screen Shot 2022-11-27 at 1 30 47 AM

The issue is that whenever React tries to render this child component for the first time, it throws the following error and none of the child components are rendered:

Screen Shot 2022-11-27 at 1 25 18 AM

A few observations:

1) If I trigger any subsequent re-renders (by clicking around in my React web app UI, for example) the child component is able to render itself and the issue seems to be resolved. So this problem only seems to occur with the first render, before the child component is mounted.

2) Removing the following line from the child component completely fixes the issue:

messagesCount: sender?.messages?.observeCount(),

This seems to be an issue seems to happen when observeCount() is executed for the very first time.

Any ideas what might be happening here? I checked the docs for any mention of best practices for mounting, but wasn't able to find anything.

ChrisSimoniMBT commented 1 year ago

Are you potentially sending undefined instead of an observer in your messages count because of lazy loading?

https://nozbe.github.io/WatermelonDB/Components.html#2nd-level-optional-relations