Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

72
Views
Continuously update state variable price from API call

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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!