-1

I have two Apine components [app1, app2] on change in app1 component storing the date value in Stores and in app2 component trying to show the stored date value. it is not showing on update.

code sandbox link

<script>
      function app1(){
        return {
          date:'2023-07-23',
          itenary:'',
        }
      }
      Alpine.store('selected_itenary', app1().itenary);
    </script>
    <script>
      function app2(){
        return {
          start_date:'2023-07-23',
        }
      }
    </script>
 <div x-data="app1()">
      <input x-model="date" type="text" class="w-48">
      <button class="rounded-md px-5 py-2 border border-gray-500" @click="$store.selected_itenary = date;">Click</button>
    </div>
    <div x-data="app2()">
        <div x-text="$store.selected_itenary"></div>
      </div>

How to bind store value in app2 component?

And also, is to correct/possible to bind only one Object entry to the store?

 Alpine.store('selected_itenary', app1().itenary);
B L Praveen
  • 1,812
  • 4
  • 35
  • 60

1 Answers1

0

I tried this out in a codepen and got it working doing 2 things:

  • Ensured the cdn script tag loading in alpinejs was deferred:
<script src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/3.12.1/cdn.js" defer></script>
  • I changed the script code to use Alpine.data:
document.addEventListener('alpine:init', () =>
    {        
        Alpine.data('app1', () => ({
        
          date:'2023-07-23',
          itenary:'2023-07-23',
        
        }));
        Alpine.store('selected_itenary', '2023-07-23');
    
        Alpine.data('app2', () => ({  
            start_date:'2023-07-23',
        }));         
    });  

After which everything worked as expected.

Yinci
  • 1,637
  • 1
  • 3
  • 14