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

210
Visualizações
How to use useState to store multiple key objects?

I have a candlestick chart for a crypto and it has different timeframe for 1 minute, 30, minute, and so on. I currently have

const [data, setData] = useState[]
  useEffect(() => {

    const fetchPrice = async () => {
      const { data } = await axios.get(`/api/apii?slug=${poolName[0].pool_id}&timeframe=`${1h}``); // default is 1h

      const btcusd = data.data.results.map(
        (d) => {
          return {
            open: d.open,
            close: d.close,
            low: d.low,
            high: d.high,
            time: toDateStamp(d.datetime),
          };
        }
      );
      setData(btcusd)
    };

    fetchPrice()
  }, []);

The above is the initial state whenever a user visits which he or she will be shown a 1-hour chart data. So there is this onClick button which will fetch and set new state according to he chosen timeframe. It works if i setData for one timeframe but then if I set another timeframe, how do I separate them?

Edit:

My bad guys, I have no issues to have the useffect runs again as i have another useeffect for that purpose whenever a user clicks on a new timeframe. My question is how can I store the chosen timeframes into a state and then re-use them again should the user chooses the timeframe that he chose before? This would be nice as I can stop outgoing network request.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

can use the spread operator inside setData() to get the old values, then add the new value, something like this:

setData( oldValues => [ ...oldValues, newValue ] );
about 4 years ago · Juan Pablo Isaza Relatório

0

You could set data as object with keys as timeframes f.e.

const [data, setData] = useState();

const TIMEFRAMES = {
  HOUR: '1h',
  HALF_HOUR: '30min',
};

const hourlyNewData = { price: 1 };

setData((prevdata) => {
  ...prevData,
  [TIMEFRAMES.HOUR]: newData,
});

const minutelyNewData = { price: 1.1 };

setData((prevData) => {
  ...prevData,
  [TIMEFRAMES.HALF_HOUR]: minutelyNewData,
});

// and to access data:
const hourlyData = data[TIMEFRAMES.HOUR];
const minutelyData = data[TIMEFRAMES.HALF_HOUR]
about 4 years ago · Juan Pablo Isaza Relatório

0

You need to add your dynamic values, like 1h and poolName to the dependency array like this:

useEffect(() => {
  ...
}, [1h, poolNames])
about 4 years ago · Juan Pablo Isaza 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