Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 490
Elom Atsou Agboka Avatar asked Dec 02 '25 10:12

Elom Atsou Agboka


1 Answers

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'] = [...];

like image 162
Dmitry S. Avatar answered Dec 03 '25 22:12

Dmitry S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!