Reputation: 125
I've been trying to follow along with a code example but I couldn't figure out what the syntax in the method updateInputValues [type]: value
means. My guess is that it updates the state variable input
based on whether the type passed in is limit or start, but I am not sure.
const [input, updateInput] = useState({ limit: 5, start: 0 })
//function to let users update input value
function updateInputValues(type, value) {
updateInput({ ...input, [type]: value })
}
//input fields to take user input
<input
onChange={e => updateInputValues('limit', e.target.value)}
placeholder="limit"
/>
<input
placeholder="start"
onChange={e => updateInputValues('start', e.target.value)}
/>
Upvotes: 0
Views: 62
Reputation: 389
This means you are setting the object key to { limit: 'value' }
or { start: 'value' }
, depending on what type is received.
When you use []
in a object key you are essentially saying resolve the key to the value of whats inside these brackets.
Computed property name: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
Upvotes: 3
Reputation: 1257
It updates the state variable using the existing state value and overriding with whatever was set by the user. You can test this out in the javascript console:
let input = { limit: 5, start: 0}
let foo = { ...input, ["limit"]: 10}
console.log(foo)
// prints {limit: 10, start: 0}
Upvotes: 2