javascriptreactjsarraysstatespread-syntax

How to Filter an Array by Another in React?


Everything that I push into arr1 should have been removed from the mapping of arr2, but instead the new pushed value is returned. Why is that?

const [arr1, setArr1] = React.useState([]);
const arr2= ['banana', 'coconut', 'milk']

React.useEffect(() => {
    initList()
}, [])

function add (t) {
    setArr1(...arr1, t.currentTarget.value)
    console.log('arr1: ' + arr1)
}

function initList () {
    setArr1(arr2.filter(arr2 => !(arr1.includes(arr2))).map(arr2 => 
        <li>
            <input
                onChange={add} 
                type='radio'
                name='arr1'
                value={arr2}
                id={arr2}
            />
            <label
                for={arr2}
            >
                {arr2}
            </label>
        </li>
    ));
}

return (
    <div>
        {arr1}
    </div>
)

Solution

    1. Do not keep the JSX elements in state (arr1). state variable to just have the data only.
    2. setArr1(...arr1, t.currentTarget.value) --> Not setting as array here. Update to setArr1([...arr1, t.currentTarget.value])

    Try the snippet.

    const Test = () => {
    const [arr1, setArr1] = React.useState([]);
    const arr2= ['banana', 'coconut', 'milk']
    
    function add (t) {
        setArr1([...arr1, t.currentTarget.value])
        console.log('arr1: ' + arr1)
    }
    
    
    return (
        <div>
            {arr2.filter(arr2 => !(arr1.includes(arr2))).map(arr2 => 
            <li>
                <input
                    onChange={add} 
                    type='radio'
                    name='arr1'
                    value={arr2}
                    id={arr2}
                />
                <label
                    for={arr2}
                >
                    {arr2}
                </label>
            </li>
        )}
        </div>
    )
    };
    
    ReactDOM.render(<Test />, document.getElementById('app'));
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    
    <div id="app"> </div>