skip to Main Content

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


  1. Unless you need otherwise I would set it up as the initial state as follows:

    const [columns, setColumns] = React.useState(
       reward_content.map((reward, idx) => <Item key={idx} value={reward} />)
    );
    

    Otherwise, a single call to setColumns using the same map should also work fine

    const [columns, setColumns] = React.useState([]);
    
    React.useEffect(() => {
      setColumns(reward_content.map((reward, idx) => <Item key={idx} value={reward} />));
    }, [])
    
    Login or Signup to reply.
  2. You should update the state variable based on previous state, use callback version of setState method as below:

    reward_content.map((reward, idx) => {
        setColumns((prevState) => [...prevState, <Item key={idx} value={reward} />]);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search