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

125
Visualizações
How do I handle updating the state of an object where data is received from multiple sources React?

Let's say I have an array of objects who's state I am interested in.

E.g. some data of the form:

const data = [{
    A: a,
    B: b,
    C: c,
    D: d
},...]

Let's assume that C and D are high cost query items, so for speed I load the page with A and B. Then, once I have A and B I go and fetch C and D items.

I fetch all data again every ... seconds, so that I have the most up to date values.

fetchAB(); // Called every x seconds
fetchCD(); // Called every y seconds

I need to map these values to a component, which should update and show the most up to date values:

const SomeComponent = () => {
    const [data, setData] = useState([]);
    
    // Some fetch logic

    return(
        {
        data.map((d, idx) => {
            return (
            <key={idx}>
                <td>{d.A}</td>
                <td>{d.B}</td>
                <td>{d.C}</td>
                <td>{d.D}</td>   
            </> 
        )}
    )}
    )
}

How do I go about updating the state of an array of mapped objects which is being updated from two (or more) sources?

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

0

I found the best way to accomplish this was to convert my array of objects into an object of objects.

This way I can use direct mapping for previous states.

E.g.

// Displaying the data structure, not actually a const. Data is returned from an API fetch.

const data = {
    1 : {
        A: a,
        B: b,
        C: c,
        D: d
    },
    2: {
        A: a,
        B: b,
        C: c,
        D: d
    },...
}

Then I can update the state like so:

var dataCD = fetchCD();
// Returns an object with id as the key, with "C, D" values.

var keys = Object.keys(dataCD);
for (var key in keys){
    data[key] = {
    ...data[key], // Include all previous data values in the object
    C: dataCD[key]["C"],
    D: dataCD[key]["D"] 
    }
}

The same logic must be implemented for all other methods updating the object state.

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