Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

78
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda