1

Basically trying to modify the dynamic search bar that can be found in Alpine docs, but with "items" ("bands" in my case) coming from x-init that fetches a JSON. Outside of this search bar all the desired data from this JSON is displayed so it's not like the JSON itself is empty, but in this particular situation x-text doesn't even list any of the values, as if the JSON data never gets to the x-data/"bands" array.

This is what I currently have, like I said it's a little modification of the search bar from the docs.

<div x-data="{
        search: '', 
        bands: [], 
        get filteredItems() {
            return this.bands.filter(
                i => i.startsWith(this.search)
            )
        }
    }"  x-init="bands = await (await fetch('/bands/')).json()">
    <input x-model="search" placeholder="Search...">
 
        <template x-for="band in filteredItems" :key="band">
            <p x-text="`${band.name}`"></p>
        </template>

</div>

I'd be grateful if anyone told me what exactly this seemingly straightforward chunk of code is missing.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
dirt1992
  • 11
  • 4
  • Are you sure your data attr is valid syntax? Ex: https://stackoverflow.com/a/38880984/8382028 – ViaTech Jan 19 '23 at 03:29
  • @ViaTech yeah absolutely, because if I replace "bands:[]" with for example some hard-coded array like "bands: ['abc', 'def', 'geh']", these values are displayed in x-text and the search works. – dirt1992 Jan 19 '23 at 03:33

1 Answers1

0
<div x-data="{search: '', bands: [], 
  get filteredItems() {
    return this.bands.filter(i => i.name.toLowerCase().includes(this.search))
    }
  }" x-init="bands = await (await fetch('/bands/')).json()">
      <input x-model="search" placeholder="Search...">
   
          <template x-for="band in filteredItems" :key="band.name">
              <p x-text="band.name"></p>
          </template>
  
  </div>

This answer was posted as an edit to the question [Solved ]Making a search bar work in AlpineJS where the searched items in x-data come from x-init by the OP dirt1992 under CC BY-SA 4.0.

vvvvv
  • 25,404
  • 19
  • 49
  • 81