Hold off on loading the slick slider until we receive a response from the API call

My slick slider was working fine, but I encountered an issue where the slider would apply before receiving a response from an API request. This is my first function:

fetchProducts () {
                this.getProducts ().then(response => {
                    const products = response.data.data;
                    this.products = products;
                    /* console.log(this.products); */
                    let element = document.getElementById("sliderContainer");
                    element.classList.add("regular");
                    this.applySlider();

                })
            },

This is the apply slider function:

applySlider() {
                if (this.products.length >= 1) {
                    $(".regular").slick({
                        //dots: true,
                        infinite: true,
                        slidesToShow: 4,
                        slidesToScroll: 4,
                        responsive: [
                            {
                            breakpoint: 992,
                            settings: {
                                slidesToShow: 3,
                                slidesToScroll: 3,
                                infinite: true,
                                dots: true,
                                arrows:false,
                            }
                            },
                            {
                            breakpoint: 768,
                            settings: {
                                slidesToShow: 2,
                                slidesToScroll: 2,
                                arrows:false,
                            }
                            },
                            {
                            breakpoint: 480,
                            settings: {
                                slidesToShow: 2,
                                slidesToScroll: 2,
                                arrows:false,
                            }
                            }
                        ]
                    });
                } 
            }

What steps can I take to resolve this issue? Thank you in advance.

Answer №1

Ensure to validate the variable (which you are assigning after receiving a response) for null value.

For example:

 applySlider() {
             if(this.products){
                if (this.products.length >= 1) {
                    $(".regular").slick({
                        //dots: true,
                        infinite: true,
                        slidesToShow: 4,
                        slidesToScroll: 4,
                        responsive: [
                            {
                            breakpoint: 992,
                            settings: {
                                slidesToShow: 3,
                                slidesToScroll: 3,
                                infinite: true,
                                dots: true,
                                arrows:false,
                            }
                            },
                            {
                            breakpoint: 768,
                            settings: {
                                slidesToShow: 2,
                                slidesToScroll: 2,
                                arrows:false,
                            }
                            },
                            {
                            breakpoint: 480,
                            settings: {
                                slidesToShow: 2,
                                slidesToScroll: 2,
                                arrows:false,
                            }
                            }
                        ]
                    });
                } 
            }
         }

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

Unusual Behavior of JavaScript for..in and enum

I'm facing an issue with the peculiar behavior of the for..in loop in JavaScript. Here's the structure of my HTML: <div id="quarter_circle_top_left">...</div> <div id="quarter_circle_top_right">...</div> <div id="quart ...

What is the best way to implement a CSS transition for styles that are dynamically created by React?

I have a situation where I am using a button component that is styled based on a theme provided by a context: The code in Button.js looks like: () => { const theme = useContext(themeContext); // { primaryColor: "blue" } return <button className ...

What could be causing the jQuery slidedown to malfunction within my table?

My slider is not working when I include a table on my website. The slider works fine without a table, but I need to display members in a table format. Can anyone help me identify the issue with my code? The information needs to be displayed below the nam ...

Learn how to mock asynchronous calls in JavaScript unit testing using Jest

I recently transitioned from Java to TypeScript and am trying to find the equivalent of java junit(Mockito) in TypeScript. In junit, we can define the behavior of dependencies and return responses based on test case demands. Is there a similar way to do t ...

What is the solution for the error message "TypeError: app.use() is seeking a middleware function"?

I am a beginner in Node.js and have encountered an issue in my passport.js or signupLogin.js file with the error message, app.use() requires a middleware function that I am struggling to resolve. I suspect it may be related to the signupLogin route, as th ...

"Error message pops up indicating the dispatcher is missing while using npm link with a local project

Currently, I am working on a React component library that I want to integrate into a local project for testing purposes. My initial approach was to use npm link to connect the component library with my local project. However, during this process, I encount ...

Extracting JSON Value from a Script Tag

Seeking a more efficient method to extract the designated JSON value (highlighted in yellow) that is currently acquired using the code below. Although effective, it lacks efficiency. $("head > script:nth-child(55)").text().trim().replace(" ...

The Json parsing failed to deserialize the API response

Struggling to send a JSON to my API, I've tried various solutions but still can't figure out what's going wrong. I'm stuck on this post call function: @PostMapping(path = "ts/sts") public void saveTestStep(@RequestBody Tes ...

Sending an array variable from Vue to scssEnsure you transmit array variable

In my Vuejs3 project with Sass, I am retrieving a list of image names from an API and want to pass it to the SCSS to dynamically write styles with background-images. export default { name: 'TestComponent', data() { return { skills: ...

Leverage and repurpose OOP objects

I am exploring how to inherit from Button using prototypes. Despite my efforts, the alerted name remains "Sarah" as it is the last Child created. I believe the Creator Class should be responsible for setting the name using a Method in Button. Check out m ...

Attempting to invoke setState on a Component before it has been mounted is not valid - tsx

I've searched through various threads regarding this issue, but none of them provided a solution that worked for me. Encountering the error: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a b ...

Redux, Retrieving the entire state rather than just the specified state

Experiencing a strange issue with react-redux. I am receiving all the state data instead of just the specific state that was passed. Here is the code snippet: Action.js import socketIOClient from 'socket.io-client' const DATA_URL = "LINK TO AP ...

Show input field depending on chosen option

I'm looking to create a dynamic form where specific input fields are displayed based on the selection made in another field. For example, if "gender: male" is selected, the input field for "blue" should appear, and if "gender: female" is selected, the ...

"Implementing a click event on a dynamically generated element is triggering the event for all of its parent elements

I have a task to generate a dynamic table with data retrieved from the server. Each row in the table contains a tag that I am trying to link to a click event. The code snippet below demonstrates how the dynamic table is created: function ProcessResponse ...

What is the best way to add child elements to existing elements?

When it comes to creating elements with jQuery, most of us are familiar with the standard method: jQuery('<div/>', { id: 'foo', href: 'http://google.com', }).appendTo('#mySelector'); However, there ar ...

Using Angular ng-repeat to iterate over a mysteriously empty Array

To display a certain element multiple times in a row, I am looking for a way that does not involve using the do(x times) function in Angular or adding extra functions in the controller. If we consider ?Array.from({length:5}) (5) [undefined, undefined, un ...

Is it possible to retrieve data from the server in Node.js/Vuetify based on a specific time frame?

I'm currently using a node.js server for my vuetify project. Within the server, I am parsing a csv file that contains scheduling and time information. Is there a method in my vuetify project to retrieve data from the csv file based on the current time ...

Window Function Implementation in AngularJS Controller

I’m encountering an issue with my AngularJS App involving a window function. Specifically, the problem lies with a window resize function. The function (someFunction()) in the controller is being triggered on every page when it should only be used with ...

How to retrieve the context of a .js file using jQuery $.ajax without automatically executing upon receipt

Upon fetching a *.js file using $.ajax, the scripts are executed upon receipt! Is there a way to fetch and execute it only when desired? Moreover, is there a method to remove these scripts at will? ...

Is it possible to integrate Google Analytics with Next.js version 13?

Is there anyone who has successfully integrated Google Analytics with NextJS 13? I tried following the steps outlined in this thread: How to implement Google Analytics with NextJS 13?, but despite doing everything as instructed, I am not seeing any data o ...