I have a component that pulls data from a store below.
When I access the render props provided, my component state does not update when the store changes.
When we don't use the render props it works as expected.
How can I access the render props and have the counter increment correctly as shown in the second example provided?
The inner function that is called with the render props is not watched by the observer function, so it does not signal that React should perform a re-render. You'll notice if you close the Popover and re-open it, the correct value appears once a re-render is forced. You should be able to fix this by wrapping the inner function in another instance of observer
:
import "./styles.css";
import testStore from "./testStore";
import { observer } from "mobx-react-lite";
import { Popover } from "@headlessui/react";
const InnerComponent = observer(({ open, close }) => (
<>
<Popover.Button>Open panel</Popover.Button>
<Popover.Panel>
<p>{testStore.counter}</p>
<button onClick={() => testStore.incrementCounter()}>Increment</button>
</Popover.Panel>
</>
));
const App = observer(() => {
console.log(testStore);
return (
<div className="App">
<Popover>
<InnerComponent />
</Popover>
</div>
);
});
export default App;
Sandbox here