Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
}
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading