'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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source