Home > Back-end >  ReactJS Array.push function does not work inside useEffect
ReactJS Array.push function does not work inside useEffect

Time:10-20

I'm trying to clear the pointLoads variable first and then add a new array to it inside the useEffect. only the counter works inside useEffect. What am I doing wrong? Here is my code.

import React, { useState, useEffect } from 'react';

const TEST = () => {
    const pointLoads = [];
    pointLoads.push([5, 0, -10], [22, 10, -200])
    const [formData, setFormData] = useState({
        "A": "9 ",
        "B": "19 ",
        "C": "9876 "
    });

    useEffect(() => {
        pointLoads.length = 0;
        pointLoads.push([formData.A, formData.B, formData.C])
    }, []);

    return (
        <div className="App">
            {pointLoads.length}
            <br />
            {pointLoads}
        </div>
    )
}

export default TEST;

CodePudding user response:

why are you using an array there if you can use a useState for the pointLoads?

Change the array for:

const [pointLoads, setPointLoads] = useState([5, 0, -10], [22, 10, -200]);

add set it: setPointLoads([formData.A, formData.B, formData.C]);

CodePudding user response:

this code is part of a larger code. I will use that table there in the future. I would like to keep an array if it is possible?

  • Related