TinaSky
TinaSky

Reputation: 39

how to use useState to handle object values?

I am new to Hook. On my project, the const state is an object, with state.boolean = false, and state.number = 1

I have an input box associate with the only the state.number, so what should my handleChange function be?

function handleChange(value){
  setState(value.number)
}

is not right.

Thanks so much

Upvotes: 0

Views: 101

Answers (2)

Javedali Hosamani
Javedali Hosamani

Reputation: 1

 Here is the answer.

const [data, setData] = useState({
                name: '',
                email: '',
                mobile: '',
                password: ''
            });
    
        const handleChange = (e) => {
            const { name, value } = e.target;
            setData({...data, [name]: value });
        }

<input type="text" name="name" id="name" className="form-control" placeholder="Full Name" required value={data.name} onChange={handleChange}/>

Upvotes: 0

Seth Lutske
Seth Lutske

Reputation: 10792

You can still update parts of an object using the useState hook and its associated setState functions:

const initialValue = {
  boolean: false,
  number: 1
}

const [value, setValue] = useState(initialValue)

function updateNumberPartOfState = number => {
  setValue({
    ...value,
    number: number
  })
}

function updateBooleanPartOfState = boolean => {
  setValue({
    ...value,
    boolean: boolean
  })
}


Or like Andrew Li commented, just have a separate setState value/function pair for each variable:

const [boolean, setBoolean] = useState(false)
const [number, setNUmber] = useState(1)

Note: don't actually use boolean or number, as these are very close to the reserved terms Boolean and Number, and I'm pretty sure typescript uses the lowercase values as reserved words.

Upvotes: 4

Related Questions