1

I have an object in my React application which is getting updated from another system. I'd like to display the properties of this object in a component, such that it updates in real time.

The object is tracked in my state manager, Jotai. I know that Jotai will only re-render my component when the actual object itself changes, not its properties. I'm not sure if that is possible.

Here is a sample that demonstrates my issue:

import React from "react";
import { Provider, atom, useAtom } from "jotai";

const myObject = { number: 0 };

const myObjectAtom = atom(myObject);

const myObjectPropertyAtom = atom((get) => {
  const obj = get(myObjectAtom)
  return obj.number
});


const ObjectDisplay = () => {
  const [myObject] = useAtom(myObjectAtom);
  const [myObjectProperty] = useAtom(myObjectPropertyAtom);
  const forceUpdate = React.useState()[1].bind(null, {});
  return (
    <div>
      {/* This doesn't update when the object updates */}
      <p>{myObject.number}</p>
      {/* This doesn't seem to work at all. */}
      <p>{myObjectProperty}</p>
      {/* I know you shouldn't do this, its just for demo */}
      <button onClick={forceUpdate}>Force Update</button>
    </div>
  );
};

const App = () => {
  // Update the object's property
  setInterval(() => {
    myObject.number += 0.1;
  }, 100);
  return (
    <Provider>
      <ObjectDisplay />
    </Provider>
  );
};

export default App;

Sandbox

Peter Edmonds
  • 355
  • 3
  • 15

1 Answers1

0

you can use useEffect for this.

useEffect(()=> {
  // code
}, [myObject.number])
Ömer Doğan
  • 501
  • 1
  • 6
  • 21
  • Thanks for the suggestion. I tried it out and it doesn't seem to work either. https://codesandbox.io/s/jotai-demo-forked-69u25h?file=/src/App.js – Peter Edmonds Mar 02 '22 at 22:14