Search code examples
nativescriptnativescript-vue

Nativescript Vue ListPicker does not update it's items


I am trying to load topics (just string values) from a backend and display them in the ListPicker. However the ListPicker won't update it's items which should be displayed.

The code is as follows:

<template>
    <Page>
        <ActionBar title="Create Challenge" icon="">
            <NavigationButton text="Back" android.systemIcon="ic_menu_back" @tap="goBack" />
        </ActionBar>

        <StackLayout>
            <Label text="TOPIC" class="fab lblSubTitle"/>
            <ListPicker :items="topics" v-model="selectedItem" />
            <Button text="check" @tap="checkIt" />
        </StackLayout>

    </Page>
</template>

<script>

    import {ObservableArray} from 'tns-core-modules/data/observable-array';
    import {FirebaseService} from '../../services/firebase-service';

    export default {

        data() {
            return {
                selectedItem: 0,
                topics: new ObservableArray(["some", "hardcoded", "items"])
            };
        },
        methods: {
            goBack() {
                this.$navigateBack();
            },
            checkIt() {
                this.topics.push("new item");
            }
        },
        created() {
            console.log("Create Challenge - Loading Topics")

            // Fetch additional items from the Firebase DB
            FirebaseService.fetchTopics().then(result => {
                result.forEach(topic => {
                    this.topics.push(topic);
                });
            });
        }
    }
</script>


<style scoped>
    .lblSubTitle {
        font-size: 15;
        margin: 10dp;
        color: red;
    }
</style>

So the FirebaseService.fetchTopics() returns an array of strings. This works perfektly fine and adds the received values to the ObserveableArray topics.
However the ListPicker only shows the hardcoded values. Not the dynamically added ones. Also the checkIt() method won't update the view.

I have tried to change topics to a conventional array with no effect.

Link to the Playground

NativeScript Version: 6.5.0
Android Device: Pixel 2 - Android 9


Solution

  • ListPicker doesn't listen to changes on ObservableArray. You must use a simple Array and mutate the changes

    this.topics = [...this.topics, "new item"];