gzai's avatar
Level 3

get array property update in javascript

hello, I have dynamic cascading dropdown list using select2.

class CitiesLivewire extends Component
{
    public $countries;
    public $states;

    public $country;
    public $state;

    public function mount()
    {
        $this->countries = MsCountries::get();
        $this->states = collect();
    }

    public function updatedCountry()
    {
        if ( $this->country != '' )
        {
            $this->states = MsStates::where('ms_country_id', $this->country )
                                        ->get();
            // dd($this->states); 
            // the result is fine
        }
    }
}

when I call it in javascript, states property doesn't change. how to get updated states property?

<script>
    $(function() {

        $('.select2-country, .select2-state').select2();
        $('.select2-country').on('change', function (e) {
            var data = $('.select2-country').select2("val");
            @this.set('country', data);

            let states = @js($states);
            console.log(states);
            // the result [] is not updated.
        });
        $('.select2-state').on('change', function (e) {
            var data = $('.select2-state').select2("val");
            @this.set('state', data);
        });

    });
</script>
0 likes
0 replies

Please or to participate in this conversation.