Maintaining responsiveness while initiating an HTTP request in a separate component

I have a specific app structure

<header-bar></header-bar>    

<bag :bag="bag"></bag>

<!--Main Section-->
<section class="MainSection">

    <div class="MainSection__wrap">
        <router-view 
            is="view" 
            transition="fade" 
            transition-mode="out-in"
            keep-alive
        >
        </router-view>
    </div>

</section>

Upon examination, there exist 2 components and a router view.

The router view displays products retrieved from an API, which can be added to the bag component.

In my products view (part of the router view), there is a method that adds items to the bag by making a POST HTTP Request to the server.

addToBag() {
   productService.add(this.item)
      .then(item => {
          console.log('success !)
      })
}

Currently, I am only able to see the items in the bag after reloading the page.

Although dispatching events could potentially solve this issue, the hierarchy of components does not permit me to use it.

Answer №1

When incorporating a new item on the server side, it is crucial to also update the item in the vm.bag dataset. One effective approach could involve utilizing Vuex for seamless integration. The primary objective here is to ensure that you can access the same "bag" from both your existing bag component and your "productService" or "addToBag" functionalities.

To achieve this synchronization, make the following adjustments within the component where the bag data is specified:

// Old Code
    /* inside component */
    data: function() {
        return {
            bag: []
        }
    }

// Updated Code
var state = {
    bag: []
}

    /* inside component */
    data: function() {
        return {
            bag: state.bag
        }
    }

Subsequently, leverage the identical bag array within your addToBag function:

addToBag() {
   productService.add(this.item)
      .then(item => {
          state.bag.push(item)
      })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to include a parameter in the current URL in Django using Paginator?

After setting up a page to display database data, I added a paginator and a search bar to my website. When a user searches for something, the URL changes to include the search query like this: .../search/?q=xyz However, when paginating the search results ...

Troubleshooting Vue.js 2: Difficulty with Vue locating files stored in the /assets directory (v-for loop)

My Vue-cli 3 project with Webpack has the following folder structure: /public /src /assets p1.jpg p2.jpg App.vue main.js I have read that in order for Webpack to recognize the /assets directory, require() should be used in JavaScript files ...

What are the implications of a project containing nested node_modules directories?

We are currently in the process of dividing our project into "sub modules" within a single repository. Our goal is to maintain aspects such as webpack configurations and express server globally, with a structure similar to the following: package.json serv ...

Having trouble with the jQuery each function's functionality

I am creating circular counters for surveys by generating a counter for each answer option. Currently, I am utilizing this "plugin": Issue: The problem lies in the plugin not fetching the text value from the <div> element and failing to draw coun ...

Leverage the power of the React useFetch hook with an onclick/event

My component utilizes a custom reusable hook for making HTTP calls. Here is how I am using it: const { data, error, isLoading, executeFetch } = useHttp<IArticle[]>('news', []); Additionally, within the same component, there is a toggle che ...

Utilizing the handleChange method to manage multiple input fields

It is important to me that the function handleChange only updates the input value that is being changed. Specifically, if I modify the 'firstName' input, I want only that state to be updated, and the same applies to the 'lastName' input ...

Use jQuery to easily update the background of an iFrame

I have implemented this code to store the background image selected from a dropdown menu labeled rds. This function also sets a cookie so that the chosen background persists even after the page is reloaded. The issue lies in the line containing $('da ...

Tips for incorporating `new google.maps.Marker()` with `vue2-google-maps` are as follows:1. First

Due to certain reasons, I find myself having to utilize new google.maps.Marker() with vue2-google-maps, but I'm unsure of where to begin as most documentation and tutorials use <GmapMarker ... /> in the HTML section instead. I've attempted ...

A guide on showcasing a value in an Input box using AngularJS

Recently, I started delving into AngularJS and I am determined to create a user info editing page where the old info is displayed in input fields. The goal is to allow users to easily see and update their information. I previously achieved this without usi ...

Using Jquery to dynamically add an active class to a link if it matches the current URL

Is there a way to modify the code below so that only the exact current URL will have the active class added? Currently, even when the URL is http://localhost/traineval/training, it also adds the active class to http://localhost/traineval/training/all_train ...

Tips for consolidating JavaScript assets in Mean.io

Recently, I started using Mean.io and encountered an issue while trying to include an external .js file in my package. Unfortunately, I seem to be doing it incorrectly as the file is not being added to aggregated.js. This is the approach I have taken: im ...

The order of event handlers in jQuery

I am currently setting up event binding for a text element dynamically. Take a look at the following code snippet: <input type="text" id="myTxt" /> <script type="text/javascript"> function attachEvent1(element){ element.keyup(func ...

Running globally installed node modules on Windows 7 is not supported

Note: Despite scouring various posts on this issue, I have not found a solution that works for me. That's why I am reaching out here. Problem: I am facing an issue while trying to set up the http-server package on my Windows 7 system using the comman ...

Importing multiple exports dynamically in Next.js

My current setup involves using a third-party package that I load dynamically in Next.js: const am5 = dynamic(() => import("@amcharts/amcharts5"), {ssr: false}) The imported amcharts5 consists of various exports and imports, such as: export { ...

What is the best way to ensure that messages stay saved in my app for an extended

I am looking for a way to store messages sent through my small messaging app in a persistent manner. Currently, the messages are transferred from the front-end to a Node, Socket.io, and Express back-end. A friend recommended using Enmaps (), but unfortuna ...

The error "converting circular structure to json" occurred when trying to create a JSON web token, resulting in an unhandled TypeError

screenshot of error I recently encountered an issue while implementing JSON web token authentication on my application. The error message displayed was: " Unhandled rejection TypeError: converting circular structure to JSON " Upon further investigation, ...

Align the fullcalendar to the present date

Is it possible to align the calendar for the current date in the center? This is how my code looks: <div id='calendar'></div> $("#calendar").fullCalendar({ height: 135 }) $('.fc-view-container').animate({ scro ...

As soon as I inserted the image, the text vanished into thin air

The phrase "welcome" is not displaying after I included the av tag <!DOCTYPE html> <html> <style> @font-face { font-family: OpenSans; src: url(OpenSans-Bold.ttf); } * { ...

Encountering invalid JSON response while making an API request

Struggling to integrate GoToMeeting's API by sending a POST request to create a meeting. Currently, attempting to manually code the meeting body and send the necessary headers, but encountering an issue with invalid JSON error. Below is the code snipp ...

Autocomplete Dropdown failing to select default value when defaultValue option is set

stateNPAValue[formData.state.vale] = 0: "All",1: "959", 2: "203",3: "860", 4: "475" // API response for NPA data const [selectedNamesState, setSelectedNamesState] = useState([]); const transformedNpaData ...