I am currently facing difficulties in updating my Component Array. My current code is as following:
import React from 'react';
import ReactDOM from 'react-dom';
const Item = ({ value }) => {
return (
<div className="col">
<div className="card" style={{width: "30rem"}}>
<img src="https://cdn.shopify.com/s/files/1/0617/1623/4396/files/Untitled_design_1.png?v=1707233721"
className="card-img-top" alt="..."/>
<div className="card-body">
<h5 class="card-title">{value.title}</h5>
<p className="card-text">{value.description}</p>
<a href="#" class="btn btn-primary">Redeem Voucher</a>
</div>
</div>
</div>
)
}
function RewardContent(props){
const reward_content = [{"id":"STORE25K","title":"25K OFF","image":"#","description":"Redeem this discount voucher to get 25.000 off.", "eligibility":"Newcomers","point_deduction":25000},
{"id":"STORE50K","title":"50K OFF","image":"#","description":"Redeem this discount voucher to get 50.000 off.", "eligibility":"Newcomers", "point_deduction":45000},
{"id":"STORE100K","title":"100K OFF","image":"#","description":"Redeem this discount voucher to get 100.000 off.", "eligibility":"Newcomers","point_deduction":90000},
{"id":"STORE150K","title":"150K OFF","image":"#","description":"Redeem this discount voucher to get 150.000 off.", "eligibility":"Newcomers","point_deduction":135000}];
const [columns, setColumns] = React.useState([]);
React.useEffect(() => {
reward_content.map((reward, idx) => {
setColumns([...columns, <Item key={idx} value={reward} />]);
});
}, [])
I am updating my array with useState inside useEffect. But somehow everytime I print and render my array, I always find out that my array still empty. I know from here that I cannot use array push for updating my array, so I use array spread instead. But, somehow it is still not working.
Please can someone spot my mistakes ? Thank You
2
Answers
Unless you need otherwise I would set it up as the initial state as follows:
Otherwise, a single call to setColumns using the same map should also work fine
You should update the state variable based on previous state, use callback version of setState method as below: