Get the updated value using setState in react native












0















**




I have a TextInput and two buttons which are responsible to increment
or decrement the value of that TextInput. Using setState I am achieving
it. Everything is fine but after setState when I am consoling the
value it is showing me the previous value, but in TextInput I am
getting the updated value. The code is the following:-




**



state = {
cartItems:[
{
id:1,
count:0
},
{
id:2,
count:0
},

],
}

changeQuantity = (productId,action)=>{
this.setState(prevState=>{
return{
cartItems:prevState.cartItems.filter(single=>{
if(single.id==productId){
if(action==='plus'){
single.count++;
}
if(action==='minus' && single.count>0){
single.count--;
}
}
return single;
})
}

})
console.log(this.state.cartItems.find(single => single.id === productId).count)

/*This gives the previous value not the updated value*/

}


Why is this happening and what is the proper way to get the updated value??










share|improve this question





























    0















    **




    I have a TextInput and two buttons which are responsible to increment
    or decrement the value of that TextInput. Using setState I am achieving
    it. Everything is fine but after setState when I am consoling the
    value it is showing me the previous value, but in TextInput I am
    getting the updated value. The code is the following:-




    **



    state = {
    cartItems:[
    {
    id:1,
    count:0
    },
    {
    id:2,
    count:0
    },

    ],
    }

    changeQuantity = (productId,action)=>{
    this.setState(prevState=>{
    return{
    cartItems:prevState.cartItems.filter(single=>{
    if(single.id==productId){
    if(action==='plus'){
    single.count++;
    }
    if(action==='minus' && single.count>0){
    single.count--;
    }
    }
    return single;
    })
    }

    })
    console.log(this.state.cartItems.find(single => single.id === productId).count)

    /*This gives the previous value not the updated value*/

    }


    Why is this happening and what is the proper way to get the updated value??










    share|improve this question



























      0












      0








      0








      **




      I have a TextInput and two buttons which are responsible to increment
      or decrement the value of that TextInput. Using setState I am achieving
      it. Everything is fine but after setState when I am consoling the
      value it is showing me the previous value, but in TextInput I am
      getting the updated value. The code is the following:-




      **



      state = {
      cartItems:[
      {
      id:1,
      count:0
      },
      {
      id:2,
      count:0
      },

      ],
      }

      changeQuantity = (productId,action)=>{
      this.setState(prevState=>{
      return{
      cartItems:prevState.cartItems.filter(single=>{
      if(single.id==productId){
      if(action==='plus'){
      single.count++;
      }
      if(action==='minus' && single.count>0){
      single.count--;
      }
      }
      return single;
      })
      }

      })
      console.log(this.state.cartItems.find(single => single.id === productId).count)

      /*This gives the previous value not the updated value*/

      }


      Why is this happening and what is the proper way to get the updated value??










      share|improve this question
















      **




      I have a TextInput and two buttons which are responsible to increment
      or decrement the value of that TextInput. Using setState I am achieving
      it. Everything is fine but after setState when I am consoling the
      value it is showing me the previous value, but in TextInput I am
      getting the updated value. The code is the following:-




      **



      state = {
      cartItems:[
      {
      id:1,
      count:0
      },
      {
      id:2,
      count:0
      },

      ],
      }

      changeQuantity = (productId,action)=>{
      this.setState(prevState=>{
      return{
      cartItems:prevState.cartItems.filter(single=>{
      if(single.id==productId){
      if(action==='plus'){
      single.count++;
      }
      if(action==='minus' && single.count>0){
      single.count--;
      }
      }
      return single;
      })
      }

      })
      console.log(this.state.cartItems.find(single => single.id === productId).count)

      /*This gives the previous value not the updated value*/

      }


      Why is this happening and what is the proper way to get the updated value??







      react-native setstate






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 15 '18 at 5:18









      Yossi

      1,7952720




      1,7952720










      asked Nov 15 '18 at 5:04









      Sandip NagSandip Nag

      140211




      140211
























          2 Answers
          2






          active

          oldest

          votes


















          3














          setState is asynchronous. The place where you have written the console.log will still have previous value hence it will show you old value. Try adding console in setState completion block to print the updated value of state.



          this.setState({
          // update your state here
          }, () => {
          console.log('Updated value ');
          });





          share|improve this answer
























          • Thank you very much, it works !

            – Sandip Nag
            Nov 15 '18 at 10:22



















          1















          It you do a console to next line after setState has been called it
          will log only previous state. I don't know why the behaviour exists. Try logging it in componentDidUpdate.







          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53312743%2fget-the-updated-value-using-setstate-in-react-native%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3














            setState is asynchronous. The place where you have written the console.log will still have previous value hence it will show you old value. Try adding console in setState completion block to print the updated value of state.



            this.setState({
            // update your state here
            }, () => {
            console.log('Updated value ');
            });





            share|improve this answer
























            • Thank you very much, it works !

              – Sandip Nag
              Nov 15 '18 at 10:22
















            3














            setState is asynchronous. The place where you have written the console.log will still have previous value hence it will show you old value. Try adding console in setState completion block to print the updated value of state.



            this.setState({
            // update your state here
            }, () => {
            console.log('Updated value ');
            });





            share|improve this answer
























            • Thank you very much, it works !

              – Sandip Nag
              Nov 15 '18 at 10:22














            3












            3








            3







            setState is asynchronous. The place where you have written the console.log will still have previous value hence it will show you old value. Try adding console in setState completion block to print the updated value of state.



            this.setState({
            // update your state here
            }, () => {
            console.log('Updated value ');
            });





            share|improve this answer













            setState is asynchronous. The place where you have written the console.log will still have previous value hence it will show you old value. Try adding console in setState completion block to print the updated value of state.



            this.setState({
            // update your state here
            }, () => {
            console.log('Updated value ');
            });






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 15 '18 at 10:14









            JiteshWJiteshW

            1,05331652




            1,05331652













            • Thank you very much, it works !

              – Sandip Nag
              Nov 15 '18 at 10:22



















            • Thank you very much, it works !

              – Sandip Nag
              Nov 15 '18 at 10:22

















            Thank you very much, it works !

            – Sandip Nag
            Nov 15 '18 at 10:22





            Thank you very much, it works !

            – Sandip Nag
            Nov 15 '18 at 10:22













            1















            It you do a console to next line after setState has been called it
            will log only previous state. I don't know why the behaviour exists. Try logging it in componentDidUpdate.







            share|improve this answer




























              1















              It you do a console to next line after setState has been called it
              will log only previous state. I don't know why the behaviour exists. Try logging it in componentDidUpdate.







              share|improve this answer


























                1












                1








                1








                It you do a console to next line after setState has been called it
                will log only previous state. I don't know why the behaviour exists. Try logging it in componentDidUpdate.







                share|improve this answer














                It you do a console to next line after setState has been called it
                will log only previous state. I don't know why the behaviour exists. Try logging it in componentDidUpdate.








                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 15 '18 at 8:26









                Naveen VigneshNaveen Vignesh

                309112




                309112






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53312743%2fget-the-updated-value-using-setstate-in-react-native%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    List item for chat from Array inside array React Native

                    Thiostrepton

                    Caerphilly