Search code examples
reactjsuse-effectuse-state

React store data from a state into another state


can anyone please help me solve this problem, I am trying to get some attribute from the tempList state to store into listReceiver state by using gosetListReceiver() function below.

const [tempList, setTempList] = useState([]); 

const [listReceiver, setListReceiver] = useState([]);


    function gosetListReceiver() {
    let i = 0;
    while (i < tempList.length) {
        setListReceiver([
            ...listReceiver,
            {
                name: tempList[i]["name"],
                phone: tempList[i]["receiver"]
            }
        ]);

        i++;
    }
}

but when I am mapping/console the listReceiver state after that , I expect that it will store 3 array from the tempList into listReceiver but it only have the last item from tempList that stored into it. how can i fix this?

below the sample data of tempList as i need to take name and receiver attribute to store into listReceiver

enter image description here


Solution

  • Every time through the loop, you are overwriting the state and thus wiping out anything you did on the last time through the loop. To fix this, you have two options.

    1. Use the function version of set state so that you always get passed in the most recent version of the state:
    setListReceiver((prev) => [
      ...prev,
      {
        name: tempList[i]["name"],
        phone: tempList[i]["receiver"],
      },
    ]);
    
    
    1. Wait until you've created the full array, and then set state just once at the end:
    function gosetListReceiver() {
      let i = 0;
      const newState = [...listReceiver];
      while (i < tempList.length) {
        newState.push({
          name: tempList[i]["name"],
          phone: tempList[i]["receiver"],
        });
    
        i++;
      }
      setListReceiver(newState);
    }
    

    P.S, this code looks like it would be better as a for loop, instead of a while loop:

    const newState = [...listReceiver];
    for (let i = 0; i < tempList.length; i++) {
      newState.push({
        name: tempList[i]["name"],
        phone: tempList[i]["receiver"],
      });
    }
    setListReceiver(newState);