简体   繁体   中英

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.

Eg 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 BI 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?

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.

Eg

// 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM