I have two state variables
const [cartList, setCartList] = useState([]);
const [tabledata, setTabledata] = useState(localStorage.getItem("items"))
tableData is initiated from local storage
cartList will be an array of objects with complete list and an example will be like
[
{id: 1, name: pen, sku: 1001, price: 5},
{id: 2, name: a4-book, sku: 1005, price: 2},
{id: 3, name: usb-16gb, sku: 1010, price: 15},
{id: 4, name: usb-32gb, sku: 1021, price: 28}
]
tableData is also an object array and will have some items and an example will be like
[
{id: 2, name: a4-book, sku: 1005, price: 1.5},
{id: 4, name: usb-32gb, sku: 1021, price: 22}
]
cartList has my latest price for each item, i want to update the tabledata to get the price for corresponding items (by id) from cartList every 5 minutes.
what is the best way to achieve this continuously ? so the tabledata element price is up to date with cartList price for corresponding items?
You can fetch cartList and update tableData and localStorage right away. However for doing this every 5 minutes, simply wrap the fetch call in a setInterval() call.
const FIVE_MINUTES_MS = 5 * 60 * 1000;
useEffect(() => {
const interval = setInterval(() => fetch("/api/cartlist")
.then(res => res.json())
.then(list => {
setCartList(list);
const tableDataNew = tableData.map(item => ({
...item,
price: list.find(cartItem => cartItem.name === item.name).price
}));
setTableData(tableDataNew);
localStorage.setItem("items", JSON.stringify(tableDataNew));
})
.catch(err => console.error(err)), FIVE_MINUTES_MS);
return () => clearInterval(interval);
}, []);
The important bit to understand here is that I copy the updated prices from cartList after it is fetched and then update tableData while also storing it in localStorage.
The return statement is to stop this process e.g. when the component unmounts.
I haven't tested this but I hope this gives an idea of the flow.