Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  160] [ 4]  / answers: 1 / hits: 5606  / 4 Years ago, wed, november 25, 2020, 12:00:00

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?


More From » arrays

 Answers
5

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


[#2227] Monday, November 23, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katianatasham

Total Points: 293
Total Questions: 110
Total Answers: 103

Location: Saint Helena
Member since Mon, Jun 28, 2021
3 Years ago
katianatasham questions
Tue, Jul 20, 21, 00:00, 3 Years ago
Thu, Mar 18, 21, 00:00, 3 Years ago
Wed, Jun 24, 20, 00:00, 4 Years ago
Fri, May 15, 20, 00:00, 4 Years ago
Wed, Apr 15, 20, 00:00, 4 Years ago
;