Make A React Component Rerender When Data Class Property Change
In my Typescript app, there's a class that represents some data. This class is being shared end to end (both front-and-back ends use it to structure the data). It has a property na
Solution 1:
Here is an example of how you can make Data instance observable and use Effect in your components to observe changes in Data instance items:
const { useState, useEffect } = React;
classData {
constructor() {
this.data = {
users: [],
products: [],
};
this.listeners = [];
}
addItem(type, newItem) {
this.data[type] = [...this.data[type], newItem];
//notify all listeners that something has been changedthis.notify();
}
addUser(user) {
this.addItem('users', user);
}
addProduct(product) {
this.addItem('products', product);
}
reset = () => {
this.data.users = [];
this.data.products = [];
this.notify();
};
notify() {
this.listeners.forEach((l) =>l(this.data));
}
addListener = (fn) => {
this.listeners.push(fn);
//return the remove listener functionreturn() =>
(this.listeners = this.listeners.filter(
(l) => l !== fn
));
};
}
const instance = newData();
let counter = 0;
setInterval(() => {
if (counter < 10) {
if (counter % 2) {
instance.addUser({ userName: counter });
} else {
instance.addProduct({ productId: counter });
}
counter++;
}
}, 500);
//custom hook to use instanceconstuseInstance = (instance, fn = (id) => id) => {
const [items, setItems] = useState(fn(instance.data));
useEffect(
() =>
instance.addListener((items) =>setItems(fn(items))),
[instance, fn]
);
return items;
};
constgetUsers = (data) => data.users;
constgetProducts = (data) => data.products;
constUsers = () => {
const users = useInstance(instance, getUsers);
return<pre>{JSON.stringify(users)}</pre>;
};
constProducts = () => {
const products = useInstance(instance, getProducts);
return<pre>{JSON.stringify(products)}</pre>;
};
constApp = () => {
constreset = () => {
instance.reset();
counter = 0;
};
return (
<div><buttononClick={reset}>Reset</button><div>
users:
<Users /></div><div>
products:
<Products /></div></div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script><divid="root"></div>
Post a Comment for "Make A React Component Rerender When Data Class Property Change"