Struggling with dataset item update...

Hi, I’m trying to update a couple of item fields in a collection when a request is “approved”. I have looked through the forum and on the API Reference and attempted to figure out what to do from there…

I’ve tried a few things but couldn’t get any to work and I don’t want to mess the code up so much that I ruin the function of the page, so now hoping to get some help.

This is the code I have atm

(the data insert is what I added first and this worked as it should have, but then I added the—
let status = “APPROVED”; let setTime = “Not Applied”;
— thinking that would work but it hasn’t, and now the refresh data function doesn’t seem to be working either)

//-------------Request Approval-------------//

// Approve the requested appointment.
async function approveRequest(pendingRequest, index) {
 // Approve the requested appointment.
 // Set the requested appointment's status to approved.
            pendingRequest.status = "APPROVED";
 // Update the requested appointment in the pendingAppointments collection. 
 await wixData.update("setlistRequests", pendingRequest);
 let toInsert = $w("#pendingRequestsDataset").getCurrentItem();
            wixData.insert("sessionLineup", toInsert)
              .then( (results) => {
 let status = "APPROVED";
 let setTime = "Not Applied";
                } )
                .catch( (err) => {
 let errorMsg = err;
                } );
 // Refresh the page's data and update page elements.
            refreshData();

    } 

@lisamthorpe I have a couple observations about the code that may be helpful in you sorting out how to make it work. Without full knowledge of everything at play here, I can’t be any more specific than this.

Mixing wixData functions with dataset functions in the same code can be dicey since a dataset’s record values often do not coincide with what is actually in the collection at that moment.

The other thing is a concept that you are apparently getting familiar with because you are using async. The refreshData function is being called way earlier than you’re hoping it is. Those data operations take a little time to execute but the code in the function continues to evaluate and that refreshData function has likely been called before the insert is finished. Try moving that line into the .then() section.

Thank you, I moved the refreshData function as you suggested and that now works :slight_smile:

I’m not completely clued up on async functions, I just know they are used to execute multiple functions that rely on a promise being resolved.

I’m very new to using Corvid and haven’t used code before so I’m just trying to figure things out as I go along.

I’ll show you an image of the page layout and explain what I’m trying to do with this section of code…

This is a version of the “pending appointments” page in the “quick book and pending appointments” example in Corvid docs (using repeaters and datasets to display and manage booking requests). But I have adapted it to what I need and have taken away the use of wixBookings (because I needed the original booking form to correlate with events dates and couldn’t find a way to make them work together).

It all works okay with the adjustments I have made, except this new bit I am trying to sort out (mentioned in my initial comment). So the bit of code above is to try and do the following:

  • When the “approve” button is clicked on a pending appointment, the relevant item is copied from the “setlistRequests” collection to “sessionLineup” (this works) and then the ‘status’ field value is changed to “APPROVED” and the ‘setTime’ value changed to “Not Applied” (this is the bit I can’t get working).

  • I’ve now removed the let status = “APPROVED” line from inside the .then function because I’ve realised that the status is changing to “approved” in the original collection because of the first pendingRequest.status = “APPROVED”; line.
    But I don’t know why that isn’t transferring to the new collection - the item’s status in the new collection remains “pending”… and the setTime field remains blank.

//-------------Request Approval-------------//

// Approve the requested appointment.
async function approveRequest(pendingRequest, index) {
 // Approve the requested appointment.
 // Set the requested appointment's status to approved.
            pendingRequest.status = "APPROVED";
 // Update the requested appointment in the pendingAppointments collection. 
 await wixData.update("setlistRequests", pendingRequest);
 let toInsert = $w("#pendingRequestsDataset").getCurrentItem();
            wixData.insert("sessionLineup", toInsert)
              .then( (results) => {
 let setTime = "Not Applied";
                   refreshData();
                } )
                .catch( (err) => {
 let errorMsg = err;
                } );

    } 

@lisamthorpe From your code I can see you are writing the pendingRequest object to the setlistRequests collection.

What collection is the pendingRequestsDataset tied to? Using getCurrentItem() will not give you the latest data for a record if you, in this same session, wrote something to that same record using the wixData commands of update and insert. Like I mentioned, that’s why you have to be careful mixing the dataset operations with wixData commands. As the Corvid documentation says about datasets: " A dataset serves as an intermediary between page elements, such as input elements and buttons, and the data in a collection."

The let setTime = “Not Applied” line is only setting a variable. I don’t see where it’s written to the collection or assigned to a page element.

@tony-brunsman The pendingRequestsDataset is tied to the setlistRequests collection.

I am literally just starting with using code on my site so my knowledge is limited and based on things I have attempted to piece together by looking things up in the forum, reference and google. I can’t seem to figure out completely how it works using code with repeaters, how to make sure the item referred to in the code is relevant to its repeater item, especially when using data collections.

getCurrentItem() is what I’m using to move add the approved item into the sessionLineup collection and it works… The only thing not happening is updating the value of the two fields in the sessionLineup colletion - setTime and status.

Honestly, I’m just kind of guessing here and maybe being really stupid but I have no idea how to go about learning all of this other than just trying to look up how to create functions and try to piece things together.

Completely understand if it would be pointless trying to help, just feeling a little lost with it atm.

Here is the whole page code if it helps…

import wixData from 'wix-data';
import wixLocation from 'wix-location';

//-------------Page Setup-------------//

$w.onReady(function () {
 // When the pending requests dataset is ready:
    $w("#pendingRequestsDataset").onReady(() => {
 // If there are no pending requests:
 if ($w("#pendingRequestsDataset").getTotalCount() === 0) {
 // Show the no pending requests message.
            $w("#noPendingRequests").show();
        }
    });
});

//-------------Repeater Setup-------------//

// Set up each item in the requests repeater as it is loaded.
export function requestsRepeater_itemReady($item, itemData, index) {

 // Set the dismiss button to dismiss the appointment request when clicked.
    $item("#dismissButton").onClick(async () => {
 // Disable the dismiss and approve buttons.
        $item("#dismissButton").disable();
        $item("#approveButton").disable();
 // Dismiss the appointment request.
 await dismissRequest(itemData, index, $w);
    });

 // Set the approve button to approve the appointment request when clicked.
    $item("#approveButton").onClick(async () => {

 // Disable the dismiss and approve buttons.
        $item("#dismissButton").disable();
        $item("#approveButton").disable();
 // Approve the appointment request.
 await approveRequest(itemData, index);
    });
}

// Set up each item in the dismissed requests repeater as it is loaded.
export function dismissedRequests_itemReady($item, itemData, index) {

 // Set the contact button to create an email to the user whose request was dismissed.
    $item("#emailButton").onClick(() => {
 const subject = "Your Setlist Request - ";
        wixLocation.to(`mailto:${itemData.email}?subject=${subject}${itemData.session}`);
    });
}

// Set up each item in the approved requests repeater as it is loaded.
export function approvedRequests_itemReady($item, itemData, index) {

 // Set the dismiss button to dismiss the appointment request when clicked.
    $item("#cancelButton").onClick(async () => {
 // Disable the dismiss and approve buttons.
        $item("#cancelButton").disable();
        $item("#timeslotButton").disable();
 // Dismiss the appointment request.
 await cancelRequest(itemData, index, $w);
    });

 // Set the approve button to approve the appointment request when clicked.
    $item("#timeslotButton").onClick(async () => {

 //Change add slot to confirm button.
        $item("#timeslotButton").hide();
        $item("#timeslotInput").show();
        $item("#confirmSlotButton").show();
    });

    $item("#confirmSlotButton").onClick(async () => {

 //Change confirm to add slot button.
        $item("#confirmSlotButton").hide();
        $item("#timeslotButton").show();
 // Confirm time slot adjustment.
 await timeslotRequest(itemData, index);
 // hide timeslotInput.
        $item("#timeslotInput").hide();
    });
}

//-------------Request Dismissal-------------//

// Dismiss the requested appointment.
async function dismissRequest(pendingRequest, index, $w) {
 // Dismiss the requested appointment.
 // Set the requested appointment's status to dismissed.
    pendingRequest.status = "DISMISSED";
 // Update the requested appointment in the pendingAppointments collection.
 await wixData.update("setlistRequests", pendingRequest);
 // Refresh the page's data and update page elements.
    refreshData();
}

//-------------Request Approval-------------//

// Approve the requested appointment.
async function approveRequest(pendingRequest, index) {
 // Approve the requested appointment.
 // Set the requested appointment's status to approved.
    pendingRequest.status = "APPROVED";
 // Update the requested appointment in the pendingAppointments collection. 
 await wixData.update("setlistRequests", pendingRequest);
 let toInsert = $w("#pendingRequestsDataset").getCurrentItem();
    wixData.insert("sessionLineup", toInsert)
        .then((results) => {
 let setTime = "Not Applied";
            refreshData();
        })
        .catch((err) => {
 let errorMsg = err;
        });

}

//-------------Time Slot Adjustment-------------//

// Dismiss the requested appointment.
async function timeslotRequest(pendingRequest, index, $w) {

 let setTimeUpdate = $w("#timeslotInput").value

 let toUpdate = {
 "setTime": setTimeUpdate
    };

    wixData.update("sessionLineup", toUpdate)
        .then((results) => {
 let item = results; //see item below
        })
        .catch((err) => {
 let errorMsg = err;
        });

    refreshData();
}

//-------------Request Cancellation-------------//

// Dismiss the requested appointment.
async function cancelRequest(pendingRequest, index, $w) {
 // Dismiss the requested appointment.
 // Set the requested appointment's status to dismissed.
    pendingRequest.status = "CANCELLED";
 // Update the requested appointment in the pendingAppointments collection.
 await wixData.update("setlistRequests", pendingRequest);
    wixData.remove("sessionLineup")
        .then((results) => {
 let item = results; //see item below
        })
        .catch((err) => {
 let errorMsg = err;
        });
 // Refresh the page's data and update page elements.
    refreshData();
}

//-------------Page Update-------------//

// Refresh the page's datasets and update all the elements that are connected to them.
function refreshData() {
 // Refresh the pending requests dataset and update all the elements that are connected to it.
    $w("#pendingRequestsDataset").refresh().then(() => {
 // If there are no pending requests:
 if ($w("#pendingRequestsDataset").getTotalCount() === 0) {
 // Show the no pending requests message.
            $w("#noPendingRequests").show();
        }
    });
 // Refresh the dismissed requests dataset and update all the elements that are connected to it.
    $w("#dismissedRequestsDataset").refresh();
    $w("#sessionLineupDataset").refresh();
}

@lisamthorpe Try this alternative to using getCurrentItem because, as mentioned, it looks like it doesn’t have the updated values at this point. This approach would.

// Approve the requested appointment.
async function approveRequest(pendingRequest, index) {
 // Approve the requested appointment.
 // Set the requested appointment's status to approved.
  pendingRequest.status = "APPROVED";
 // Update the requested appointment in the pendingAppointments collection. 
    wixData.update("setlistRequests", pendingRequest)
    .then((updateResults) => {
        updateResults.setTime = "Not Applied";
        wixData.insert("sessionLineup", updateResults)
        .then( (results) => {
                refreshData();
        } )
        .catch( (err) => {
          let errorMsg = err;
        } );        
    })

}

THANK YOU!! Works perfectly.
If you don’t mind me picking your lovely brains just a teensy bit more…

I’ve tried to update data in another bit of code on this page and that isn’t working either - relevant to the same setTime field updated in the code you suggested above.
But i can’t get that working either, I tried to adapt what you gave me for the other issue but that didn’t work.

The add slot (timeslotButton) is to be used to update the time slot for the approved request. But as before, I can’t get the field to update in the data collection.

No idea what I have or haven’t done but here’s the code…

export function approvedRequests_itemReady($item, itemData, index) {

 // Set the dismiss button to dismiss the appointment request when clicked.
    $item("#cancelButton").onClick(async () => {
 // Disable the dismiss and approve buttons.
        $item("#cancelButton").disable();
        $item("#timeslotButton").disable();
 // Dismiss the appointment request.
 await cancelRequest(itemData, index, $w);
    });

 // Set the approve button to approve the appointment request when clicked.
    $item("#timeslotButton").onClick(async () => {

 //Change add slot to confirm button.
        $item("#timeslotButton").hide();
        $item("#timeslotInput").show();
        $item("#confirmSlotButton").show();
    });

    $item("#confirmSlotButton").onClick(async () => {

 //Change confirm to add slot button.
        $item("#confirmSlotButton").hide();
        $item("#timeslotButton").show();
 // Confirm time slot adjustment.
 await timeslotRequest(itemData, index);
 // hide timeslotInput.
        $item("#timeslotInput").hide();
    });
}

and then this is the timeSlotRequest function referred to in the above await function


//-------------Time Slot Adjustment-------------//

// Dismiss the requested appointment.
async function timeslotRequest(updateResults, index, $w) {

updateResults.setTime = $w("#timeslotInput").value;
        wixData.update("sessionLineup", updateResults)
        .then( (results) => {
                refreshData();
        } )
        .catch( (err) => {
 let errorMsg = err;
        } );        
}