D
D
drotsyk2021-02-04 15:33:55
React
drotsyk, 2021-02-04 15:33:55

Why is new data not being written to state?

Why is an empty string written to state and not all values ​​from localStorage?

export class Cart extends React.Component {
  state = {
    arrFromLocal:'',
  }
  componentDidMount(){
    var values = [],
    keys = Object.keys(localStorage),
    i = keys.length;
    while ( i-- ) {
      values.push(localStorage.getItem(keys[i]) );
    }
    this.setState({
      arrFromLocal: values
    },console.log(this.state.arrFromLocal, values))
  }

at the same time, all objects are stored in the values ​​variable but are not assigned via setState

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-02-04
@drotsyk

The state is updated asynchronously. The callback is passed as the second argument.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question