Elom Atsou Agboka
Elom Atsou Agboka

Reputation: 45

Redux - Data Store - Don't understand this syntax

I am studying React.js and I am on the Redux section.

There is this code, I don't understand why it is written like this. It is explaining the creation of the initial state of a data store. And it is explained that redux uses pure JavaScript.

src/store/initialData.js

import { PRODUCTS, SUPPLIERS } from "./dataTypes";
export const initialData = {
    [PRODUCTS]: [
        { id: 1, name: "Trail Shoes", category: "Running", price: 100 },
        { id: 2, name: "Thermal Hat", category: "Running", price: 12 },
        { id: 3, name: "Heated Gloves", category: "Running", price: 82.50 }],
    [SUPPLIERS]: [
        { id: 1, name: "Zoom Shoes", city: "London", products: [1] },
        { id: 2, name: "Cosy Gear", city: "New York", products: [2, 3] }],
}

src/store/dataTypes.js

export const PRODUCTS = "products";
export const SUPPLIERS = "suppliers";

My question is that why is there a syntax like this :

[PRODUCT]: [...]

I just don't understand the square brackets around PRODUCT. I've never seen this syntax before when defining object. Can someone explain that syntax to me?

Upvotes: 3

Views: 73

Answers (1)

Dmitry S.
Dmitry S.

Reputation: 8513

This is a JavaScript/ECMAScript specific question. When you can assign a constant property name to an object pretty easily using the dot notation:

const initialData = {};
initialData.products = [...];

However, in that case PRODUCTS is a dynamic imported value. Therefore, you have to use the bracket notation to assign such a property:

import { PRODUCTS } from './dataTypes';

const initialData = {};
initialData[PRODUCTS] = [...];

You can also do something like:

const initialData = {};
initialData['pro' + 'ducts'] = [...];

Upvotes: 1

Related Questions