Home > other >  Saving data in useState variable with select form in React
Saving data in useState variable with select form in React

Time:02-08

I have an array of objects which contain properties of their size and quantity (FE: {size:"Large", quantity: 10}). I want the user to be able to select any available size in the form and then store it in useState. To be honset I do something like that for the first time and sadly my code is not working. I get basillion errors starting with "event is undeffined". I'm pasting my code below:

    const handleChange = (event) => {
        setChosenSize(event.target.value)
    }

    const choseSize = (array) => {
        return (<>
             <form>
                <label>Choos your size:</label>
                <select onChange={() => handleChange()}>
                    {array.map((object) => {
                    return (
                        <option value={object.size}>{object.size}: {object.quantity}</option>
                    )
                    })}
                </select>
            </form>
        </>)
    }
    console.log(chosenSize)

CodePudding user response:

You are running the function without passing anything inside it so event will either be undefined or null. The following should fix your problem:

const handleChange = (event) => {
        setChosenSize(event.target.value)
    }

    const choseSize = (array) => {
        return (<>
             <form>
                <label>Choos your size:</label>
                <select onChange={(event) => handleChange(event)}>
                    {array.map((object) => {
                    return (
                        <option value={object.size}>{object.size}: {object.quantity}</option>
                    )
                    })}
                </select>
            </form>
        </>)
    }
    console.log(chosenSize)

or you can do the following (which I prefer)

const handleChange = (event) => {
        setChosenSize(event.target.value)
    }

    const choseSize = (array) => {
        return (<>
             <form>
                <label>Choos your size:</label>
                <select onChange={handleChange}>
                    {array.map((object) => {
                    return (
                        <option value={object.size}>{object.size}: {object.quantity}</option>
                    )
                    })}
                </select>
            </form>
        </>)
    }
    console.log(chosenSize)
  •  Tags:  
  • Related