I'm trying to figure out a way to add objects into my array. Here's the code.
export default function DashboardTable(props) {
const { transactionData } = props;
const classes = useStyles();
const [transactionDataArray, setTransactionDataArray] = useState([])
useEffect(() => {
setTransactionDataArray(transactionDataArray.push(transactionData))
}, [transactionData])
console.log(transactionDataArray);
transactionData returns objects (the amount of objects is variable depending on the back end transactions.) I want to add the objects to the array transactionDataArray
but I keep getting the error transactionDataArray is not a function
. Where am I going wrong?
I'm trying to figure out a way to add objects into my array. Here's the code.
export default function DashboardTable(props) {
const { transactionData } = props;
const classes = useStyles();
const [transactionDataArray, setTransactionDataArray] = useState([])
useEffect(() => {
setTransactionDataArray(transactionDataArray.push(transactionData))
}, [transactionData])
console.log(transactionDataArray);
transactionData returns objects (the amount of objects is variable depending on the back end transactions.) I want to add the objects to the array transactionDataArray
but I keep getting the error transactionDataArray is not a function
. Where am I going wrong?
Array.prototype.push
actually does. It does not return the updated array, it returns the length of the new array. In addition, push
mutates the original array which is against the rules of React state.
– Brian Thompson
Commented
Nov 25, 2020 at 16:34
Yes, you can use push in useEffect but not on the state. React state can not be changed directly. As being a state you can not directly push or edit data of the state transactionDataArray
. But with the help of setTransactionDataArray
function you can change/set the state value. so for you to add new value to it's older state you have to destructure the old state and add the new value like below
setTransactionDataArray([...transactionDataArray, transactionData])
or you can do it like below by creating new variable assigning state's value and than push the new value to the variable and last set the state
const data = transactionDataArray;
data.push(transactionData);
setTransactionDataArray(data);
for more about react state read here
To add data to your local state you don't have to use push but only "setTransactionDataArray" because that's the function that will add data to state.
So in your useEffect
useEffect(() => {
setTransactionDataArray(transactionData)
}, [transactionData])
Or if you want to have an array with data then later add that array to state than you should declare an array and add data to it. Then when the job is done you can add that array in state.