Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions in React: my function isn't working, because of 'read-only' error. Why?

I'm trying to write a function into a React component, but I am stuck with this error:

Uncaught Error: Module build failed: SyntaxError: "productMap" is read-only

Why is this happening? And how can I fix this, so I can use productMap?

Here is my function:

printReceipt() {
    var products = this.props.updateBasket.products;

    //create a map of products

    const productMap = {};
    for(let product of products) {
        if(!productMap[product.id]) {
            productMap[product.id] = 1;
        } else {
            productMap = productMap + 1; 
        }
    }
    console.log(productMap);
}
like image 932
user74843 Avatar asked Mar 02 '18 14:03

user74843


2 Answers

This is happening because poductMap is of type const and const cannot change through reassignment

Change it to a let or var instead

printReceipt() {
    var products = this.props.updateBasket.products;

    //create a map of products

    let productMap = {};
    for(let product of products) {
        if(!productMap[product.id]) {
            productMap[product.id] = 1;
        } else {
            productMap = productMap + 1; 
        }
    }
    console.log(productMap);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

like image 155
Galupuf Avatar answered Sep 30 '22 00:09

Galupuf


Use let productMap={}; instead of const.

The const declaration creates a read-only reference to a value.

Reference

like image 39
Amanshu Kataria Avatar answered Sep 30 '22 00:09

Amanshu Kataria