Search code examples
javascriptreactjsreact-state-management

State value goes empty to child component


I'm trying to send information from parent to child component with a state.

In the parent component, I'm getting the value and storing it inside an array named valueArray. Later on, this array will be stored in a state and sent through child component to map and display the values.

1-) Function below takes the values selected by user and pushes them inside an empty array valueArray.

let valueArray = [];
    const getSelectedItem = (event) =>{

        if(valueArray.includes(item)){
            valueArray.splice(item.index,1);
           
        }else{
            valueArray.push(item);
        }
       
    }

2-) In here, after user done with selecting values, another function to store values in state will be initiated by onClick, this function uses valueArray as argument.

<button onClick={() => handleState(valueArray)}>Buton</button> 

3-) After the button click, handleState function executes and updates state with the elements in valueArray, values array goes to child component to map and perform display.

    const [values,setValues] = useState([]);
    const handleState = (arr) =>{
            setValues([...arr])     
    }

Major problem in here is, when button clicked at the first time after selection, state becomes empty array and child component can't execute mapping because valueArray's initial value is []. Second click works and state changes with values inside the valueArray.


Solution

  • Use State like this.

     const [valueArray, setValueArray] = [];
        const getSelectedItem = (event) =>{
        const array = [...valueArray]; 
            if(array.includes(item)){
                array.splice(item.index, 1);
                // setValueArray([...valueArray.filter((ite) => ite != item)]);
                setValueArray([...array]);
               
            }else{
                // valueArray.push(item);
                 setValueArray([...array, item]); // instead of push we should use spread or concat()
            }
           
        }