JavaScript componentDidMount updating synchronously

I'm loading data from saved session using:

componentDidMount() {
    if (JSON.parse(localStorage.getItem('savedData')) !== null) {
        this.setState({
            cartItems: JSON.parse(localStorage.getItem('savedData')),
            totalPrice: this.getPriceOnLoad(),
            totalItems: this.getItemsOnLoad(),
        });
    }
}

cartItems is an array of objects. Which seems is updated before

this.getPriceOnLoad();
this.getItemsOnLoad();

functions are called, for example this.getPriceOnLoad function:

getPriceOnLoad() {
    let itemsPrice = 0;
    for (let i = 0; i <= this.state.cartItems.length - 1; i++) {
        itemsPrice += this.state.cartItems[i].quantity * this.state.cartItems[i].price;
    }
    return itemsPrice;
}

but, in getPriceOnLoad function, this.state.cartItems.length is equal to 0, so for loop is not executing. I can see in React dev tools that this array has some length. Is it because componentDidMount() is executing state change synchronously and can't see updated array immediately? So my question is how could i update price and quantity of items after array is initialized?

Answer:1

Your state is not updated in order. For this, you could store the cartItems in a temporary value, and send it to each functions :

componentDidMount() {
    if (JSON.parse(localStorage.getItem('savedData')) !== null) {
        const cartItems = JSON.parse(localStorage.getItem('savedData'))
        this.setState({
            cartItems, //Short syntax for 'cartItems: cartItems'
            totalPrice: this.getPriceOnLoad(cartItems),
            totalItems: this.getItemsOnLoad(cartItems),
        });
    }
}

You could also make your function significantly shorter by using reduce:

this.setState({
    cartItems,
    totalPrice: cartItems.reduce((total, item) => total + (item.quantity * item.price), 0),
    totalItems: cartItems.reduce((total, item) => total + item.quantity, 0),
});

Can you show us your second function too ? It may be optimized as well. Done.

Answer:2

the wrong thing that you are doing is trying to use values from the state on your functions that will define your state.

you have 2 approaches to solve this:

1) use the callback function from setState and then set the state again with the new data (which into my opinion is not the best approach)

componentDidMount() {
    if (JSON.parse(localStorage.getItem('savedData')) !== null) {
        const cartItems = JSON.parse(localStorage.getItem('savedData'))
        this.setState({
            cartItems
        }, ()=> {
           this.setState({
            totalPrice: this.getPriceOnLoad(cartItems),
            totalItems: this.getItemsOnLoad(cartItems),
           });
        })
    }
}

2) send the values to your functions

componentDidMount() {
    if (JSON.parse(localStorage.getItem('savedData')) !== null) {
        const savedCartItems = JSON.parse(localStorage.getItem('savedData'))
        this.setState({
            cartItems,
            totalPrice: this.getPriceOnLoad(savedCartItems),
            totalItems: this.getItemsOnLoad(savedCartItems),
        });
    }
}
Answer:3

is there some simple way how to read POST request parameters in nuxtjs asyncData function? Thanks a lot. Here's an example: Form.vue: <template> <form method="post" action="/clickout" ...

is there some simple way how to read POST request parameters in nuxtjs asyncData function? Thanks a lot. Here's an example: Form.vue: <template> <form method="post" action="/clickout" ...

  1. read post request python
  2. read post request php
  3. read post request node js
  4. read post request body c#
  5. read post request flask
  6. read post request body java
  7. read post request javascript
  8. read post request c#
  9. read post request
  10. read post request java
  11. read post request body javascript
  12. php read post request body
  13. golang read post request
  14. express read post request body
  15. arduino read post request
  16. django read post request
  17. express read post request
  18. read json post request java
  19. esp8266 read post request
  20. node read post request

I'm starting work on a members section of my website, using AngularJS. v0.1.0.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title><?php ...

I'm starting work on a members section of my website, using AngularJS. v0.1.0.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title><?php ...

  1. angular error module not found
  2. angular error module
  3. angular error module can't import itself
  4. angular error ts2305 module
  5. angular error handling module
  6. angular mat-error module
  7. angular error unexpected module
  8. angular error loading module
  9. angular error cannot find module 'node-sass'
  10. angular error cannot find module
  11. angular error cannot find module 'webpack'
  12. angular error cannot find module 'tslib'
  13. angular error cannot find module 'typescript'
  14. angular error cannot find module 'symbol-observable'
  15. angular error cannot find module '../lib/init'
  16. angular injector module error
  17. angular error not a module
  18. angular error loading chunk module failed
  19. angular error cannot find module 'rxjs-compat/observable'
  20. angular error cannot find module 'debug'

I've been doing JS development for a long time now, and for years I thought I could short circuit a conditional statement using the logical AND. In fact, I do this ALL THE TIME in my React components ...

I've been doing JS development for a long time now, and for years I thought I could short circuit a conditional statement using the logical AND. In fact, I do this ALL THE TIME in my React components ...

  1. does javascript have classes
  2. does javascript need semicolons
  3. does javascript pass by reference
  4. does javascript have pointers
  5. does javascript compile
  6. does javascript short circuit
  7. does javascript have garbage collection
  8. does javascript have inheritance
  9. does javascript use semicolons
  10. does javascript have interfaces
  11. does javascript have dictionaries
  12. does javascript have a garbage collector
  13. does javascript have enums
  14. does javascript have tuples
  15. does javascript follow pemdas
  16. does javascript have a main function
  17. does javascript have integers
  18. does javascript run on jvm
  19. does javascript have sets
  20. does javascript have hashmap

I am trying to get value from two fields using the jQuery autocomplete with PHP, but I am not able to able to get the data. index.php: var availableTags = <?php include('autocomplete.php'); ?>;...

I am trying to get value from two fields using the jQuery autocomplete with PHP, but I am not able to able to get the data. index.php: var availableTags = <?php include('autocomplete.php'); ?>;...

  1. issue regarding with
  2. regarding issue of debentures
  3. regarding your issue with