Why does a reload return an empty state half of the time?Why does Google prepend while(1); to their JSON responses?Why does ++[[]][+[]]+[+[]] return the string “10”?Why does parseInt(1/0, 19) return 18?vuex commit does not commit to storeHow to check if Vuex state object is emptyWhen should I use component data instead of vuex state?Vuex store not returning right valueVuex persistedstate reset logged in userHow to get value from state as my vuex getter is returning empty value in observerVuex getter not updating on state changes

What's the relationship betweeen MS-DOS and XENIX?

Escape Velocity - Won't the orbital path just become larger with higher initial velocity?

How to measure if Scrum Master is making a difference and when to give up

What would cause a nuclear power plant to break down after 2000 years, but not sooner?

What should we do with manuals from the 80s?

Are there really no countries that protect Freedom of Speech as the United States does?

Go to last file in vim

What are the advantages of this gold finger shape?

Why aren’t there water shutoff valves for each room?

The more + the + comparative degree

Why aren't rainbows blurred-out into nothing after they are produced?

Cycle of actions and voice signals on a multipitch climb

Least cost swapping in C++

Doubt in a simple problem related to geometric mean

Is Thieves' Cant a language?

Is it possible to know the exact chord from the roman numerals

Is there any official ruling on how characters go from 0th to 1st level in a class?

Graphs for which a calculus student can reasonably compute the arclength

How can I find an old paper when the usual methods fail?

Why aren't rockets built with truss structures inside their fuel & oxidizer tanks to increase structural strength?

Why do so many people play out of turn on the last lead?

Does an Irish VISA WARNING count as "refused entry at the border of any country other than the UK?"

Scam? Phone call from "Department of Social Security" asking me to call back

How would armour (and combat) change if the fighter didn't need to actually wear it?



Why does a reload return an empty state half of the time?


Why does Google prepend while(1); to their JSON responses?Why does ++[[]][+[]]+[+[]] return the string “10”?Why does parseInt(1/0, 19) return 18?vuex commit does not commit to storeHow to check if Vuex state object is emptyWhen should I use component data instead of vuex state?Vuex store not returning right valueVuex persistedstate reset logged in userHow to get value from state as my vuex getter is returning empty value in observerVuex getter not updating on state changes






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I'm creating a webshop for a hobby project in Nuxt 2.5. In the Vuex store I have a module with a state "currentCart". In here I store an object with an ID and an array of products. I get the cart from the backend with an ID, which is stored in a cookie (with js-cookie).



I use nuxtServerInit to get the cart from the backend. Then I store it in the state. Then in the component, I try to get the state and display the number of articles in the cart, if the cart is null, I display "0". This gives weird results. Half of the time it says correctly how many products there are, but the Vuex dev tools tells me the cart is null. The other half of the time it displays "0".



At first I had a middleware which fired an action in the store which set the cart. This didn't work consistently at all. Then I tried to set the store with nuxtServerInit, which actually worked right. Apparently I changed something, because today it gives the descibed problem. I can't find out why it produces this problem.



The nuxtServerInit:



nuxtServerInit ( commit , req ) 
let cartCookie;

// Check if there's a cookie available
if(req.headers.cookie)

cartCookie = req.headers.cookie
.split(";")
.find(c => c.trim().startsWith("Cart="));

// Check if there's a cookie for the cart
if(cartCookie)
cartCookie = cartCookie.split("=");
else
cartCookie = null;

// Check if the cart cookie is set
if(cartCookie)

// Check if the cart cookie isn't empty
if(cartCookie[1] != 'undefined')
let cartId = cartCookie[1];

// Get the cart from the backend
this.$axios.get(`$api/$cartId`)
.then((response) =>
let cart = response.data;
// Set the cart in the state
commit("cart/setCart", cart);
);


else
// Clear the cart in the state
commit("cart/clearCart");

,


The mutation:



setCart(state, cart) 
state.currentCart = cart;



The getter:



currentCart(state) 
return state.currentCart;



In cart.vue:



if(this.$store.getters['cart/currentCart'])
return this.$store.getters['cart/currentCart'].products.length;
else
return 0;


The state object:



const state = () => (
currentCart: null,
);


I put console.logs everywhere, to check where it goes wrong. The nuxtServerInit works, the commit "cart/setCart" fires and has the right content. In the getter, most of the time I get a null. If I reload the page quickly after another reload, I get the right cart in the getter and the component got the right count. The Vue dev tool says the currentCart state is null, even if the component displays the data I expect.



I changed the state object to "currentCart: " and now it works most of the time, but every 3/4 reloads it returns an empty object. So apparently the getter fires before the state is set, while the state is set by nuxtServerInit. Is that right? If so, why is that and how do I change it?



What is it I fail to understand? I'm totally confused.










share|improve this question
































    1















    I'm creating a webshop for a hobby project in Nuxt 2.5. In the Vuex store I have a module with a state "currentCart". In here I store an object with an ID and an array of products. I get the cart from the backend with an ID, which is stored in a cookie (with js-cookie).



    I use nuxtServerInit to get the cart from the backend. Then I store it in the state. Then in the component, I try to get the state and display the number of articles in the cart, if the cart is null, I display "0". This gives weird results. Half of the time it says correctly how many products there are, but the Vuex dev tools tells me the cart is null. The other half of the time it displays "0".



    At first I had a middleware which fired an action in the store which set the cart. This didn't work consistently at all. Then I tried to set the store with nuxtServerInit, which actually worked right. Apparently I changed something, because today it gives the descibed problem. I can't find out why it produces this problem.



    The nuxtServerInit:



    nuxtServerInit ( commit , req ) 
    let cartCookie;

    // Check if there's a cookie available
    if(req.headers.cookie)

    cartCookie = req.headers.cookie
    .split(";")
    .find(c => c.trim().startsWith("Cart="));

    // Check if there's a cookie for the cart
    if(cartCookie)
    cartCookie = cartCookie.split("=");
    else
    cartCookie = null;

    // Check if the cart cookie is set
    if(cartCookie)

    // Check if the cart cookie isn't empty
    if(cartCookie[1] != 'undefined')
    let cartId = cartCookie[1];

    // Get the cart from the backend
    this.$axios.get(`$api/$cartId`)
    .then((response) =>
    let cart = response.data;
    // Set the cart in the state
    commit("cart/setCart", cart);
    );


    else
    // Clear the cart in the state
    commit("cart/clearCart");

    ,


    The mutation:



    setCart(state, cart) 
    state.currentCart = cart;



    The getter:



    currentCart(state) 
    return state.currentCart;



    In cart.vue:



    if(this.$store.getters['cart/currentCart'])
    return this.$store.getters['cart/currentCart'].products.length;
    else
    return 0;


    The state object:



    const state = () => (
    currentCart: null,
    );


    I put console.logs everywhere, to check where it goes wrong. The nuxtServerInit works, the commit "cart/setCart" fires and has the right content. In the getter, most of the time I get a null. If I reload the page quickly after another reload, I get the right cart in the getter and the component got the right count. The Vue dev tool says the currentCart state is null, even if the component displays the data I expect.



    I changed the state object to "currentCart: " and now it works most of the time, but every 3/4 reloads it returns an empty object. So apparently the getter fires before the state is set, while the state is set by nuxtServerInit. Is that right? If so, why is that and how do I change it?



    What is it I fail to understand? I'm totally confused.










    share|improve this question




























      1












      1








      1








      I'm creating a webshop for a hobby project in Nuxt 2.5. In the Vuex store I have a module with a state "currentCart". In here I store an object with an ID and an array of products. I get the cart from the backend with an ID, which is stored in a cookie (with js-cookie).



      I use nuxtServerInit to get the cart from the backend. Then I store it in the state. Then in the component, I try to get the state and display the number of articles in the cart, if the cart is null, I display "0". This gives weird results. Half of the time it says correctly how many products there are, but the Vuex dev tools tells me the cart is null. The other half of the time it displays "0".



      At first I had a middleware which fired an action in the store which set the cart. This didn't work consistently at all. Then I tried to set the store with nuxtServerInit, which actually worked right. Apparently I changed something, because today it gives the descibed problem. I can't find out why it produces this problem.



      The nuxtServerInit:



      nuxtServerInit ( commit , req ) 
      let cartCookie;

      // Check if there's a cookie available
      if(req.headers.cookie)

      cartCookie = req.headers.cookie
      .split(";")
      .find(c => c.trim().startsWith("Cart="));

      // Check if there's a cookie for the cart
      if(cartCookie)
      cartCookie = cartCookie.split("=");
      else
      cartCookie = null;

      // Check if the cart cookie is set
      if(cartCookie)

      // Check if the cart cookie isn't empty
      if(cartCookie[1] != 'undefined')
      let cartId = cartCookie[1];

      // Get the cart from the backend
      this.$axios.get(`$api/$cartId`)
      .then((response) =>
      let cart = response.data;
      // Set the cart in the state
      commit("cart/setCart", cart);
      );


      else
      // Clear the cart in the state
      commit("cart/clearCart");

      ,


      The mutation:



      setCart(state, cart) 
      state.currentCart = cart;



      The getter:



      currentCart(state) 
      return state.currentCart;



      In cart.vue:



      if(this.$store.getters['cart/currentCart'])
      return this.$store.getters['cart/currentCart'].products.length;
      else
      return 0;


      The state object:



      const state = () => (
      currentCart: null,
      );


      I put console.logs everywhere, to check where it goes wrong. The nuxtServerInit works, the commit "cart/setCart" fires and has the right content. In the getter, most of the time I get a null. If I reload the page quickly after another reload, I get the right cart in the getter and the component got the right count. The Vue dev tool says the currentCart state is null, even if the component displays the data I expect.



      I changed the state object to "currentCart: " and now it works most of the time, but every 3/4 reloads it returns an empty object. So apparently the getter fires before the state is set, while the state is set by nuxtServerInit. Is that right? If so, why is that and how do I change it?



      What is it I fail to understand? I'm totally confused.










      share|improve this question
















      I'm creating a webshop for a hobby project in Nuxt 2.5. In the Vuex store I have a module with a state "currentCart". In here I store an object with an ID and an array of products. I get the cart from the backend with an ID, which is stored in a cookie (with js-cookie).



      I use nuxtServerInit to get the cart from the backend. Then I store it in the state. Then in the component, I try to get the state and display the number of articles in the cart, if the cart is null, I display "0". This gives weird results. Half of the time it says correctly how many products there are, but the Vuex dev tools tells me the cart is null. The other half of the time it displays "0".



      At first I had a middleware which fired an action in the store which set the cart. This didn't work consistently at all. Then I tried to set the store with nuxtServerInit, which actually worked right. Apparently I changed something, because today it gives the descibed problem. I can't find out why it produces this problem.



      The nuxtServerInit:



      nuxtServerInit ( commit , req ) 
      let cartCookie;

      // Check if there's a cookie available
      if(req.headers.cookie)

      cartCookie = req.headers.cookie
      .split(";")
      .find(c => c.trim().startsWith("Cart="));

      // Check if there's a cookie for the cart
      if(cartCookie)
      cartCookie = cartCookie.split("=");
      else
      cartCookie = null;

      // Check if the cart cookie is set
      if(cartCookie)

      // Check if the cart cookie isn't empty
      if(cartCookie[1] != 'undefined')
      let cartId = cartCookie[1];

      // Get the cart from the backend
      this.$axios.get(`$api/$cartId`)
      .then((response) =>
      let cart = response.data;
      // Set the cart in the state
      commit("cart/setCart", cart);
      );


      else
      // Clear the cart in the state
      commit("cart/clearCart");

      ,


      The mutation:



      setCart(state, cart) 
      state.currentCart = cart;



      The getter:



      currentCart(state) 
      return state.currentCart;



      In cart.vue:



      if(this.$store.getters['cart/currentCart'])
      return this.$store.getters['cart/currentCart'].products.length;
      else
      return 0;


      The state object:



      const state = () => (
      currentCart: null,
      );


      I put console.logs everywhere, to check where it goes wrong. The nuxtServerInit works, the commit "cart/setCart" fires and has the right content. In the getter, most of the time I get a null. If I reload the page quickly after another reload, I get the right cart in the getter and the component got the right count. The Vue dev tool says the currentCart state is null, even if the component displays the data I expect.



      I changed the state object to "currentCart: " and now it works most of the time, but every 3/4 reloads it returns an empty object. So apparently the getter fires before the state is set, while the state is set by nuxtServerInit. Is that right? If so, why is that and how do I change it?



      What is it I fail to understand? I'm totally confused.







      javascript vue.js vuex nuxt






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 27 at 11:50







      Maurits de Ruiter

















      asked Mar 27 at 11:40









      Maurits de RuiterMaurits de Ruiter

      166 bronze badges




      166 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          1














          So, you know that moment you typed out the problem to ask on Stackoverflow and after submitting you got some new ideas to try out? This was one of them.



          I edited the question to tell when I changed the state object to an empty object, it sometimes returned an empty object. Then it hit me, the getter is sometimes firing before the nuxtServerInit. In the documentation it states:




          Note: Asynchronous nuxtServerInit actions must return a Promise or leverage async/await to allow the nuxt server to wait on them.




          I changed nuxtServerInit to this:



          async nuxtServerInit ( commit , req ) {
          ...
          await this.$axios.get(`$api/$cartId`)
          .then((response) =>
          ...

          await commit("cart/clearCart");


          So now Nuxt can wait for the results. The Dev Tools still show an empty state, but I think that is a bug, since I can use the store state perfectly fine in the rest of the app.






          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%2f55376329%2fwhy-does-a-reload-return-an-empty-state-half-of-the-time%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            So, you know that moment you typed out the problem to ask on Stackoverflow and after submitting you got some new ideas to try out? This was one of them.



            I edited the question to tell when I changed the state object to an empty object, it sometimes returned an empty object. Then it hit me, the getter is sometimes firing before the nuxtServerInit. In the documentation it states:




            Note: Asynchronous nuxtServerInit actions must return a Promise or leverage async/await to allow the nuxt server to wait on them.




            I changed nuxtServerInit to this:



            async nuxtServerInit ( commit , req ) {
            ...
            await this.$axios.get(`$api/$cartId`)
            .then((response) =>
            ...

            await commit("cart/clearCart");


            So now Nuxt can wait for the results. The Dev Tools still show an empty state, but I think that is a bug, since I can use the store state perfectly fine in the rest of the app.






            share|improve this answer





























              1














              So, you know that moment you typed out the problem to ask on Stackoverflow and after submitting you got some new ideas to try out? This was one of them.



              I edited the question to tell when I changed the state object to an empty object, it sometimes returned an empty object. Then it hit me, the getter is sometimes firing before the nuxtServerInit. In the documentation it states:




              Note: Asynchronous nuxtServerInit actions must return a Promise or leverage async/await to allow the nuxt server to wait on them.




              I changed nuxtServerInit to this:



              async nuxtServerInit ( commit , req ) {
              ...
              await this.$axios.get(`$api/$cartId`)
              .then((response) =>
              ...

              await commit("cart/clearCart");


              So now Nuxt can wait for the results. The Dev Tools still show an empty state, but I think that is a bug, since I can use the store state perfectly fine in the rest of the app.






              share|improve this answer



























                1












                1








                1







                So, you know that moment you typed out the problem to ask on Stackoverflow and after submitting you got some new ideas to try out? This was one of them.



                I edited the question to tell when I changed the state object to an empty object, it sometimes returned an empty object. Then it hit me, the getter is sometimes firing before the nuxtServerInit. In the documentation it states:




                Note: Asynchronous nuxtServerInit actions must return a Promise or leverage async/await to allow the nuxt server to wait on them.




                I changed nuxtServerInit to this:



                async nuxtServerInit ( commit , req ) {
                ...
                await this.$axios.get(`$api/$cartId`)
                .then((response) =>
                ...

                await commit("cart/clearCart");


                So now Nuxt can wait for the results. The Dev Tools still show an empty state, but I think that is a bug, since I can use the store state perfectly fine in the rest of the app.






                share|improve this answer













                So, you know that moment you typed out the problem to ask on Stackoverflow and after submitting you got some new ideas to try out? This was one of them.



                I edited the question to tell when I changed the state object to an empty object, it sometimes returned an empty object. Then it hit me, the getter is sometimes firing before the nuxtServerInit. In the documentation it states:




                Note: Asynchronous nuxtServerInit actions must return a Promise or leverage async/await to allow the nuxt server to wait on them.




                I changed nuxtServerInit to this:



                async nuxtServerInit ( commit , req ) {
                ...
                await this.$axios.get(`$api/$cartId`)
                .then((response) =>
                ...

                await commit("cart/clearCart");


                So now Nuxt can wait for the results. The Dev Tools still show an empty state, but I think that is a bug, since I can use the store state perfectly fine in the rest of the app.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 27 at 12:27









                Maurits de RuiterMaurits de Ruiter

                166 bronze badges




                166 bronze badges





















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    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%2f55376329%2fwhy-does-a-reload-return-an-empty-state-half-of-the-time%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

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해