Goal: I would like to press a button and then run a script that I've created called doSomething(), but pass along some arguments, i.e.: doSomething('Some custom text');
And then run this script from multiple places, but adjust the argument depending on each situation. So from one button I might call doSomething('Some text'), while I would run the script from a different place, using doSomething('A different text').
Steps: I have created a JS Query to "Run JS Code" and then attempted various pieces of JavaScript, like return function(text) { ... } or var doSomething = function(text) { ... }, or export function()... You get the idea.
Details: It seems like I can't provide any arguments when I use Run script as a handler. I've tried to use additionalScope as instructed by the docs, but that only seems to apply to Database Queries.
I hope this will be enough info to help me out. I'm really struggling with this seemingly small issue.
Functions are created in a separate place in retool apps, they aren't just scripts you can call.
Go to the functions tab, create a new one, and then you can define parameters and name your functions. You can read about sync functions here, be sure to read the update too (tldr; can use positional params or named params).
Once set up, you can just call them like regular functions elsewhere in your app.
just thought i'd add a little info on why your code doesn't work.
each JS Code query is basically a function itself. so if you have a JS Code query (we'll name it query1) and you define a function in here (lets say function1) it's only accessible from within query1. now if you go and make another query, query2 it's able to see that query1 exists, but it's unable to look inside of query1 and see that there's a nested function named function1. it's similiar to the situation below:
function query1() {
const doSomething = function(input_text) {
console.log(input_text);
return input_text;
}
return doSomething("AND DO IT NOW!");
}
function query2(){
const query1_ret = query1(); // prints 'AND DO IT NOW!'
console.log(query1_ret) // prints 'AND DO IT NOW!'
// error doSomething(String) is undefined
const fail_ret = doSomething("funny please")
return query1_ret;
}
const ret1 = query1() // prints 'AND DO IT NOW'
const ret2 = query2() // prints 'AND DO IT NOW'
// error doSomething(String) is undefined
const ret3 = doSomehting("no dont do it")
// error query1 is not a class or object
const ret4 = query1.doSomething("no dont do it")
I agree with both @MikeCB and @emozio -- you are not able to return functions from js queries directly, but we do have a Functions feature in a beta right now -- if you'd like to join just DM me your org name!
One small caveat -- unfortunately we haven't added Run function as a native option for event handlers yet, so the best way to call the function from a button's event handler is probably to select Run script and call function1(...) from the script body.