How do you declare and use a persistent backend variable?
I’m probably missing something obvious here…
I have two separate functions in a backend module.
They are called by separate actions on the page.
I need to set a variable value in the first function, and reference that in the second function.
This variable must remain in the backend.
e.g.
-------------------------------------------------------------------------------------
// page code
import {getFilename, downloadFile} from 'backend/dropbox';
someButton_click() {
getFileName()
.then( (fName) {
// display fName on page
$w('#someText').text = fName;
$w('#nextButton').enable();
})
}
nextButton_click() {
downloadFile();
}
-------------------------------------------------------------------------------------
// jsw code
var fileId;
export function getFileName() {
// fetch specific file info from Dropbox,
.then( (fileInfo) {
fileid = fileInfo.id; <----- THIS DOESN'T WORK
return fileInfo.name;
})
}
export function downloadFile() {
console.log(fileId) <----- fileId has not been updated by the previous function
//download the file using fileId
}
-------------------------------------------------------------------------------------
You shouldn’t do it this way.
You shouldn’t declare a variable in the global scope of a backend file unless it’s const.
The best way will be to declare it inside the first function, to return both name and id to the front-end, and to call the next function with the returned id.
@jonatandor35 But I need to keep the variable value away from the front end for security. I appreciate you taking the time to reply, and to point out an error in my nonsense code. How do you accomplish this without the value going to the front end?
@wix47224 If you put it in the global scope other users might override it. You should remember that the backend servers more than one user.
You can of course save it with a temporary id.
For example:
let fileIds = [];
export function number1 (){
//get your file, then:
let tempId = "a random string you create on the fly";
fileIds.push({tempId: tempId , fileId: fileInfo.id});
//...
return [fileInfo.name, tempId];
}
/// You call the 2nd function with the returned tempId
export function number2 (tempId ){
const fileId = fileIds .find(e => e.tempId === tempId).fileId;
//etc..
}
However, I’m not sure you can rely on that, you don’t have any control over it and Wix can clean it up.
You should consider storing it in a collection and retrieving it back.