Search code examples
javascriptreactjsreact-nativereact-hooksstate

How to update array of objects in react native useState inside for loop?


I have a state containing array of objects that I want to update my object inside for loop. Here is my codes: Each objects contain value, text and time. The time should update inside for loop.

const [initialValues, setInitialValue] = useState([
        {
            value: 128,
            text: '128 Kb',
            time: ''
        },
        {
            value: 256,
            text: '256 Kb',
            time: ''
        },
        {
            value: 512,
            text: '512 Kb',
            time: ''
        },
        {
            value: 750,
            text: '750 Kb',
            time: ''
        },
        {
            value: 1024,
            text: '1 MB',
            time: ''
        },
        {
            value: 2048,
            text: '2 MB',
            time: ''
        },
        {
            value: 3072,
            text: '3 MB',
            time: ''
        },
        {
            value: 4096,
            text: '4 MB',
            time: ''
        },
        {
            value: 5120,
            text: '5 MB',
            time: ''
        }
    ]);

The for loop where I want to update my state: The calculate is a function that will be called on onPress event from user side.

const [number, setNumber] = useState('1')
const [data, setData] = useState('1024')
const calculate = () => {
        if (number) {

            let size = number * data * 8
            size = percentage(12, size) + size;

            for (let value of initialValues) {
                let data = value.value;
                data = (size / data).toFixed();
                // here is my approach but not correct
                setInitialValue({ ...initialValues, time: data })

            }
        }
    }

But the result is undefined.


Solution

  • You should change your calculate function to this

    const calculate = () => {
    if (number) {
        let size = number * data * 8;
        size = percentage(12, size) + size;
        const newValues = [...initialValues.slice()];
    
        for (let i = 0; i < newValues.length; i++) {
            let data = (size / data).toFixed();
            newValues[i].time = data;
        }
    
        setInitialValue(newValues);
    }
    }