Wait until a svelte store value is set to true before fetching data (TypeScript)

I have implemented a pop-up prompt that requests the user's year group. Since I have databases for each year group, I need to trigger a function once the value of userInfo changes to true.

My JavaScript skills are limited, and my experience has been primarily with async calls and promises related to API fetching. This is what I currently have:

Here's an example:

onMount(async function check() {
        // Verify if the user has entered their information
        if ($userInfo) {
            getYearGroupSchedule($yeargroup, weekdates);
        } else {
            // Wait for userInfo to be true
        }
    });

I'm not sure if this is the correct approach, and I feel quite lost. Any assistance would be greatly appreciated. Feel free to ask any clarifying questions in the comments below.

Answer №1

In the onMount method, logic is executed only once. However, if you need to wait for a certain condition, it's recommended to use a reactive statement:

$: if ($userInfo) {
    getYearGroupSchedule($yeargroup, weekdates);
}

This will be checked and run every time there is a change in any of the dependent variables, including $yeargroup and weekdates. If you want the code to trigger based on a specific condition only, you can call a function to isolate that condition and "hide" the others. For example:

$: if ($userInfo) update();

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

Tips on utilizing variables instead of static values when calling objects in JavaScript

How can I make something like this work? I tried putting the variable in [], but it didn't work. Can someone please help me out with this? Thank you. const obj = { car : "a" , bus: "b" }; const x = "car" ; ...

What are the distinctions in type-narrowing when assigning values using ternary expressions versus if-else statements?

It seems that the type checker is handling the typing of m in print() differently based on whether m was assigned through a ternary expression or an if-else statement. What sets apart the first line in the print() function from the commented code below it? ...

The dropdown selection for redirecting to a URL is malfunctioning within a PHP while loop

<?php $sql = "select * from letter where societyn='" . $_SESSION['socityname'] ."' "; $result = mysql_query($sql); $i=1; while($row=mysql_fetch_array($result)){ ?> <?php $id = $row['id']; ...

What could be causing the React-Router-Dom Outlet to not show the component?

I am working on a component that houses four different components. const ProtectedRoute = () => { return ( <> <Header /> <div className='flex h-screen overflow-hidden'> <div className="md:block h ...

Troubleshooting Next.js and Tailwind CSS Breakpoints: What's causing the

Having trouble with my custom breakpoints. For instance, I attempted the following: <div className="flex flex-row gap-5 mb-5 md:ml-15 sm:ml-15"> ... </div> The margin is not being applied on small and medium screens. Here are the th ...

What could be causing the unexpected behavior of angular.isNumber()?

I'm encountering an issue with AngularJS's angular.isNumber, as it doesn't seem to work with strings that represent numbers. Is there a mistake on my end? Would utilizing isNaN() be a better approach? angular.isNumber('95.55') == ...

Unable to physically tap on the checkbox input, though able to perceive the value it holds

When running my protractor test, I encountered an issue with the following statement: await element(by.model('publishCtrl.isPublishedInAllRegions')).click(); The test failed and returned an error message stating "ElementNotVisibleError: element ...

After clicking the create button in AngularJS, the ngModel values become empty

My form has been simplified by using ngRepeat to create the input fields. The attributes for each item are defined in my controller. Below is the code for the ModalCtrl: ... $scope.form = [ { label: 'First Name', fieldType: 't ...

Sending a Thunk to the store using Typescript

Within my primary store.ts file, the following code is present: const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)) ); store.dispatch(fetchUser()); Upon initial rendering, an action is dispatched to fetchUser in ord ...

Exploring data elements using iteration in JavaScript

Here is some code that is functioning properly: Morris.Bar({ element: 'barchart', axes: true, data: [ json.bar.bar1 ], xkey: 'x', ykeys: ['y', 'z', ' ...

Utilize JavaScript to assign a value to a concealed Pardot field

Recently, I've been working on setting a hidden Pardot field within an iframe. Oddly enough, when I manually input the query selector in my Chrome console, I successfully locate the element. However, when running this code snippet (embedded in the &l ...

Using scale transformations to animate SVG group elements

I am currently experimenting with an SVG example where I hover over specific elements to expand or scale them. However, I seem to have made a mistake somewhere or missed something important. Can someone offer me assistance? View the demo on JSFiddle here ...

Establishing a connection between MySQL database and an Ionic/Angular application

I have been working on an Ionic/Angular project and I'm facing difficulties in establishing a connection with my MySQL database (mariadb). Despite trying various solutions from online sources, I keep encountering numerous error messages. Any guidance ...

Obtain the total views for a particular map

Looking to optimize my use of the Google Maps JavaScript API. Any suggestions on where I can find information on tracking views and SEO for my map? Appreciate any assistance you can provide. ...

What is the process for obtaining a push key in Firebase?

When a user submits data to the Firebase database, I need to handle the Key generated by that action in my own function. The challenge arises when a user fills out a form and sends data to our real-time DB. This data may include optional images, and I wan ...

The persistentFilter in the Tabulator is failing to verify for the headerFilterEmptyCheck

Using Tabulator version 4.4.3 When filtering the checkbox in the usual way, everything works fine. If I set a filtered checkbox to true on a column, it functions correctly: headerFilterEmptyCheck: function (value) { return !value; }, Howev ...

Get access to the file upload field using ajax

I'm encountering an issue with accessing the file upload field //HTML <input type='file' name='images' id="images" multiple> ////////////////// $('.bt-add-com').click(function(){ var formdata = new For ...

The customer's status cannot be determined

I've encountered an issue with my TypeScript code that includes a simple if-else logic. endDate: String = ''; customerStatus: String; this.endDate = this.sampleData.customerStartDate; if (this.endDate == null) { this.customerStatus = ' ...

Manipulating toggle buttons using CSS and jQuery

Check out this jsfiddle to see my attempt at creating a toggle switch in the form of a mute button. The toggle button shows the current setting: mute or unmute When hovered over, it displays the alternative setting However, I am encountering an issue wh ...

Dynamic import of a SASS file in VueJS using a variable such as process.env

Is there a way to dynamically import a file using environment variables? I want to include a specific client's general theme SCSS to my app.vue (or main.ts) I'm thinking of something along the lines of: <style lang="sass"> @import"./th ...