Purging the JavaScript output

Currently, I am calling an API and receiving a list of results. These results are then processed into an object for iteration and display.

Below is the function responsible for this process:

    var getAvailability = () => {
        if (chosenData.hotel == "") {
            showError("Please select a location before booking.");
            $timeout(() => LTBNavService.setTab('location'), 50);
            return;
        }

        searchResponse = {};
        console.log(searchResponse);
        WebAPI.getHotelAvailability(genSearchObject()).then((data) => {
            searchResponse = data;
            $timeout(() => $('[data-tab-content] .search-btn').first().focus(), 50);
            generateRoomTypeObject(searchResponse);
        }, (data) => searchResponse.error = data.data.errors[0].error);

    };

The Issue: The previous results remain visible until the new results are loaded, causing an unwanted flicker and delay in user experience.

The proposed solution (requiring assistance): What would be the most effective method to address this issue? Ideally, I aim to clear or reset the search response to display only the newest set of results. Is it feasible to achieve this within the getAvailability function?

How can this best be achieved?

Answer â„–1

The Resolution:

Credit to @Daniel Beck for recommending that I invoke the generateRoomTypeObject function with an empty object, earning a +1 on his helpful suggestion.

Upon following this advice, it became apparent that my generateRoomTypeObject function was throwing an undefined error due to performing length checks on an empty object (which logically resulted in errors). To rectify this issue, I implemented a mechanism to manage the undefined exception by assigning searchResponse to an empty object.

var generateRoomTypeObject = (searchResponse) => {
    var ratePlans = searchResponse.ratePlans,
        errors = searchResponse.error,
        roomTypes = [],
        ignoreBiggerRooms = false;
    rawRoomsObjs = [];
    if (angular.isUndefined(errors)) {
        // Iterate over the rate plan
        if(ratePlans === undefined){   
            //generateRoomTypeObject -- Handle undefined by creating new object
            searchResponse =  {}
        } else {
            for (var i = 0; i < ratePlans.length; i++) {
                var ratePlan = ratePlans[i],
                rooms = ratePlan.rooms;
                // Iterate over the rooms and add rooms to room object. Also keep a list of room types.
                for (var j = 0; j < rooms.length; j++) {
                    //Stuff here
                 }
            }
        }
    }
}

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

The array contains no elements, yet it is not empty, and when stringified with JSON.stringify, it results

I've been working on developing an event registration page for a school club I'm involved in, but I'm encountering a problem where my program is unable to correctly read the contents of an array and display each item as a ListItem within a L ...

Enhance the functionality of JavaScript for multiple images using ASP.NET

I have been searching extensively for a way to achieve the following necessary function. Initially, I successfully replicated this function in an asp.net application using VB for a single image. However, I am now attempting to apply it to multiple images. ...

Combining two JSON objects with sailsjs-nodejs to create a single merged object

Hello everyone, I am a beginner with Sailsjs-Nodejs. Currently, I have two JSON Objects in my controller that I need to merge/join in order to create a third object to send as a response. The output when using res.send(obj1) is: [ { total_fare: "37 ...

Performing queries using the ORM Sequelize to fetch data from two separate tables simultaneously during a single page

I have encountered a challenge while working on my project. I need to display data from two different tables on one page (page.hbs). My tech stack includes Node.js ORM Sequelize, MySQL database, and Handlebars for templating. However, I am facing difficult ...

Using jQuery to apply CSS to elements with multiple potential values

Here's a simple question: using jQuery's css function, you can retrieve the computed style of a CSS attribute. But what if there are multiple styles for that attribute being rendered simultaneously? Let's consider this example: <div id=" ...

Experiencing a [$compile:multidir] error when attempting to implement a multiselect dropdown with Angular.js

I encountered an issue when utilizing a multi-select drop-down list in Angular.js. Error: angularjs.js:107 Error: [$compile:multidir] http://errors.angularjs.org/1.4.6/$compile/multidir?p0=ngDropdownMultiselec…22%20checkboxes%3D%22tr ...

Assign a background image to a button using an element that is already present on the page

Is there a way to set the background-image of a button without using an image URL? I am hoping to use an element already in the DOM as the background-image to avoid fetching it again when the button is clicked. For example, caching a loading gif within the ...

obtain a dynamic key to retrieve a corresponding label text

I am currently working on an app that needs to support multiple languages. This means I have 2 separate files with key-pair label texts for different languages. Now, in a particular scenario, I need to retrieve an ID from the server and use it to display a ...

Creating easy nested list views in React Native using object data structures

I am working with an array of objects that contains user data like this: const userList = [ { "firstName": "John", "lastName": "Doe", "date": "19 March 2018" }, { "firstName": "Anna", ...

Tips on importing anime js after it has been successfully installed through npm

Today, I added anime js as a dependency to my package.json file. The version 3.0.1 is visible in the dependencies list. I used npm to install it. Next step was creating a folder and a JavaScript file in the public directory. I set up a simple event liste ...

"Incorporate keyframes to create a mouseleave event with a distinctive reverse fade

After posing a similar question a few days back, I find myself encountering yet another hurdle in my project. The task at hand is to switch the background image when hovering over a button with a fade-in effect using @keyframes. However, I'm stuck bec ...

What could be causing the RTCPeerConnection icegatheringstatechange to not function properly?

I have been trying to utilize the icegatheringstatechange event handler, but it doesn't seem to be functioning properly. Is there a different method I can use to monitor changes in icegatheringstate? How can I determine when all ice candidates have be ...

Enhancing State in React Component through Prop Update

I am aiming to achieve the functionality of clicking a button in a child component and having that component removed. I am new to React and currently in my app.js file, I have a component with a prop like this: <IntroSteps isHidden={false} /> Inside ...

Irreparable Glitches in Mocha

While developing a blogging platform, everything ran smoothly when tested on a web server. However, I encountered some issues when trying to write unit tests using Mocha and Should.js. Surprisingly, errors kept popping up where they shouldn't have bee ...

Is there a way to customize the color of a MUI styled component?

I have a customized MUI component that displays a circular badge in green. const StyledGreenBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', ...

Before the async function, make sure to set the value using React's useState

Exploring the world of react context api for the very first time. Below is my react code utilizing the context api: const [valChanged, setValChanged] = useState(false); async function modalSave() { await setValChanged(true); // STEP 1 await o ...

Unable to conceal adjacent element when z-index is set as 1

I encountered an issue where a modal is overlapping another element, and the close button of the underlying element has a z-index of 1. Despite creating a new modal with its own close button, the original close button remains visible on top. I attempted t ...

Mismatch between the format and extension of an HTML table when exporting to Excel

I've been working on a function that converts an HTML table into an Excel document. Unfortunately, when I try to open the file in Excel, I receive an error message that says: The file format and extension of 'something.xls' don't mat ...

You have exceeded the maximum number of Facebook application requests allowed (#4)

My goal is to create a dynamic "social wall" on a website by pulling posts from a specific Facebook page using the Facebook API. Instead of utilizing any Facebook SDK, I am making cURL calls with the URLs directly. To fetch the posts, I rely on Javascript ...

What is the method for defining the maximum selectable month in mtz.monthpicker?

(edited) Currently, I am utilizing the jquery.mtz.monthpicker plugin along with jquery. My goal is to limit the selection of future months, but it appears that there are no options similar to 'maxDate' like in jquery.ui.datepicker. $('inp ...