Hotwire Discussion

Basic Questions about Passing Data Types

I’m trying to figure out how to pass arrays and objects data back and forth to controller values.

Suppose I have a controller:

<div data-controller="archive" data-archive-terms-value="[]"></div>

And some button somewhere like:

<button data-archive-target="filterButton" data-value="(an array or object here)" data-action="click->archive#updateTerms"></button>

In the updateTerms function, how do I pass an array back to data-archive-terms-value? I can pass a string or a number back, but I don’t know how to properly “prepare” the array or object data so that the data value attribute on the controller is updated. It always resolves to [] when I set this.termsValue to the new array or object.

For the similarly clueless here is what I determined:

	updateTerms() {
		const dropdown = event.target;
		const term = $(dropdown).val();
		const tax = $(dropdown).find('option:selected').attr('data-taxonomy');
		let value = this.termsValue;
		value[tax] = term;
		this.termsValue = value;
	}

And then make sure the data-archive-terms-value attribute is set to {} by default:

data-archive-terms-value="{}"