0

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)}
/>
user2805620
  • 125
  • 1
  • 1
  • 13
  • It's setting the key to `type` just as you would say `input[type] = value` discussion of object literals here: [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal/2274327) – pilchard Oct 03 '20 at 00:35

2 Answers2

3

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

Emilio
  • 389
  • 1
  • 8
2

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}
dwosk
  • 1,202
  • 8
  • 11