# Is it possible to update the state object and access the updated state object in a same function

**URL:** <https://forum.codewithmosh.com/t/is-it-possible-to-update-the-state-object-and-access-the-updated-state-object-in-a-same-function/6820>\
**Category:** React\
**Created:** [August 16, 2021, 5:06am UTC](https://forum.codewithmosh.com/t/is-it-possible-to-update-the-state-object-and-access-the-updated-state-object-in-a-same-function/6820 "2021-08-16T05:06:25Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![dwstyagi](https://avatars.discourse-cdn.com/v4/letter/d/f05b48/32.png) [@dwstyagi](https://forum.codewithmosh.com/u/dwstyagi)\
**Post date:** [August 16, 2021, 5:06am UTC](https://forum.codewithmosh.com/t/is-it-possible-to-update-the-state-object-and-access-the-updated-state-object-in-a-same-function/6820/1 "2021-08-16T05:06:25Z")

</div>

```auto
state = {
    a: 1,
    b: 2,
  };

  updateState = () => {
    const { a, b } = this.state;

    console.log("previous a", a);
    console.log("previous b", b);

    this.setState({ a: b, b: 3 });

    console.log("New a", a); <-- getting previous value here
    console.log("New b", b); <-- getting previous value here

  };

is it possible to get a new value in the same function?
```

---

<div class="post-metadata">

**Author:** ![SAM](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/sam/32/167_2.png) [@SAM](https://forum.codewithmosh.com/u/SAM)\
**Post date:** [August 16, 2021, 5:14am UTC](https://forum.codewithmosh.com/t/is-it-possible-to-update-the-state-object-and-access-the-updated-state-object-in-a-same-function/6820/2 "2021-08-16T05:14:45Z")

</div>

No. But setState has a second parameter where you can supply a function that gets called after the state has been updated (and the component has been re-rendered). However usually it’s better to use componentDidUpdate() instead.

---

<div class="post-metadata">

**Author:** ![dwstyagi](https://avatars.discourse-cdn.com/v4/letter/d/f05b48/32.png) [@dwstyagi](https://forum.codewithmosh.com/u/dwstyagi)\
**Post date:** [August 30, 2021, 12:05pm UTC](https://forum.codewithmosh.com/t/is-it-possible-to-update-the-state-object-and-access-the-updated-state-object-in-a-same-function/6820/3 "2021-08-30T12:05:52Z")

</div>

can you show me how componentDidUpdate() applies here?

---

<div class="post-metadata">

**Author:** ![SAM](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/sam/32/167_2.png) [@SAM](https://forum.codewithmosh.com/u/SAM)\
**Post date:** [August 30, 2021, 3:45pm UTC](https://forum.codewithmosh.com/t/is-it-possible-to-update-the-state-object-and-access-the-updated-state-object-in-a-same-function/6820/4 "2021-08-30T15:45:53Z")

</div>

```javascript
componentDidUpdate(prevProps, prevState) {
   if (this.state.b != prevState.b) {
      console.log("previous b", prevState.b);
      console.log("new b", this.state.b);
   }
}

```
