3

Look at the example here:

https://github.com/rackt/redux/blob/master/examples/real-world/actions/index.js

return {
    [CALL_API]: {
      types: [ USER_REQUEST, USER_SUCCESS, USER_FAILURE ],
      endpoint: `users/${login}`,
      schema: Schemas.USER
    }
}

CALL_API is in square brackets so I assumed maybe it was an array and this was a destructuring thing.

But CALL_API is defined as

export const CALL_API = Symbol('Call API')

So it's not an array or anything. I've also seen the use of square braces with non-symbols. So what's the difference between

CALL_API: {}

and

[CALL_API]: {}
m0meni
  • 16,006
  • 16
  • 82
  • 141

2 Answers2

7

This is a computed property - it's the equivalent of:

let result = {}
result[CALL_API] = { ... };
return result;

Combining this with Symbol lets the library author create a protocol that will not collide with other protocols (e. g. if the protocol was a string "call" then it could collide with other libraries that use someObject.call for their (unrelated) protocols - as well as colliding with Function.prototype.call.)

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
3

What this is doing is taking the value of the express [CALL_API] and using it as the key, thus setting the key dynamically.

Example:

var x = "hello";
var y = {
  [x]: "world"
};

console.log(y); // Object {hello: "world"}

After some testing, I recommend being very careful with this. The following is perfectly valid:

var x = {"will": "this work?"};
var y = {[x]: "let's see"};

console.log(y); // Object {[object Object]: "let's see"}
console.log(y['[object Object]']); // "let's see"
Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128