Home > Mobile >  use of conventional Javascript classes for models in React
use of conventional Javascript classes for models in React

Time:12-13

Is it possible to use conventional Javascript classes in models (in a MVC paradigm) using React instead of using Redux or contexts & reducers that seem to undermine reusability? If so, how can we effectively 'subscribe' to actions that change data in these objects so that views (i.e. React components) are rendered effectively?

CodePudding user response:

The subscription logic is on you to figure out yourself. React doesn't offer any mechanism that can be "borrowed" in other classes. But event-oriented programming in Javascript is, of course, nothing new. So an event-emitter like pattern would work. So here is one example (not tested, but it should give you the idea):

class MyClass {

  data = {};

  constructor(onTick) {
    setInterval(() => {
      const now = new Date();
      this.data.time = now;
      this.data.tillChristmas = (new Date('2021-12-25')) - now;
      onTick && onTick(this);
    }, 10 * 1e3);
  }
}

const MyComp = () => {

  const [data, setData] = useState({});
  useEffect(() => {
      new MyClass(myclass => {
        setData(myclass.data);
      });
    }, []);

  return <pre>
    {JSON.stringify(data, true, 2)}
  </pre>;
  // of course, you could present the data in more interesting ways, too.
};
  • Related