Skip to content
Advertisement

How to replace Array in useState?

I want make program that table content is changed by user’s select. So I put empty array in useState, like this.

    const [statInfo, setStatInfo] = useState([]);

And select html code:

                    <select
                        name="statSelect"
                        onChange={(e) => {
                            handleChange(e);
                            setStat();
                        }}>
                        <option value="0to60">무각 60</option>
                        <option value="1to60">1각 60</option>
                        <option value="2to60">2각 60</option>
                    </select>

When I select option, data will be changed. But I don’t no how to do it with useState. These are data

    const stat = [
         [11421, 1059, 782, "10%", "50%", "10%", "25%"],
         [11992, 1112, 821, "15%", "55%", "20%", "30%"],
         [10401, 1114, 1049, "20%", "30%", "35%", "25%"]
    ];

And my React code:

    async function setStat() {
    console.log('calling');
    if (stat === "무각 60") {
        await setStatInfo(stat[0]);
        console.log(statInfo);
    } else if (stat === "1각 60") {
        await setStatInfo(stat[1]);
        console.log(statInfo);
    } else {
        await setStatInfo(stat[2]);
        console.log(statInfo);
    }
}

I tried using map. But I don’t know how to use map, too.

Is there a function or way to change the entire array each time?

Advertisement

Answer

I guess you can handle this action in your handleChange :

  handleChange(e) {
    stat.forEach(async (att) => {
      if(att === e.target.value){
        await setStatInfo(att)
      }
    })
  }

If you can’t and you want to use your setStat function I guess you can make something like :

 setStat = async (e) => {
   stat.forEach(async (att) => {
     if(att === e.target.value){
       await setStatInfo(att)
     }
   })
 }

And call this.setStat(e) in your onChange

Advertisement