Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

73
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda