Category: How do I do X?
Updated

This solution is summarized from an archived support forum post. This information may have changed. If you notice an error, please let us know in Discord.

Populate table with queries linked to buttons

Issue

I have a table and three queries, and I want to populate the table based on which button is clicked. I need to find a way to do this with just one table and multiple buttons rather than using multiple tables like in the previously answered question. My goal is to use Appsmith and its storeValue function to create this functionality.

Resolution

To populate a table with data based on which button is clicked, you can use the Appsmith storeValue function. Firstly, create one store variable to store a flag value based on the button that was clicked. Secondly, write a JS function to conditionally run and store the results of the queries in another store variable based on whichever button was clicked. On the Table widget Default Value property bind the value of the second store variable using {{appsmith.store.var2}}.

For example, let's say you have three buttons named 'Button1', 'Button2' and 'Button3', and three queries for each button named 'Query1', 'Query2', and 'Query3' respectively. Firstly, create a store variable named 'buttonClicked' and set its initial value as 'none'. Secondly, write a JS function that will run the corresponding query and store the results based on which button is clicked. Here's an example code snippet:

if (store.get('buttonClicked') === 'Button1') {
const result = await api.query({ Query1 });
store.set('results', result);
}
else if (store.get('buttonClicked') === 'Button2') {
const result = await api.query({ Query2 });
store.set('results', result);
}
else if (store.get('buttonClicked') === 'Button3') {
const result = await api.query({ Query3 });
store.set('results', result);
}

Next, add an onClick action to each button which sets the value of 'buttonClicked' store variable as the name of the button that was clicked, like this:

store.setValue('buttonClicked', 'Button1') // add this onClick of Button1
store.setValue('buttonClicked', 'Button2') // add this onClick of Button2
store.setValue('buttonClicked', 'Button3') // add this onClick of Button3

Finally, bind the results to the Table widget using the following syntax in the Default Value property:

{{ appsmith.store.results }}

With this approach, the table will be populated with data depending on which button is clicked.