Jake_James
Jake_James

Reputation: 53

Vue.js 2 & Axios - Filtering an api for a search feature

I'm trying to filter through a collection of films that i'm retrieving using axios. This is so i can compare it to a search string for a search feature. Everything works fine except when using the computed property it returns Cannot read property 'filter' of undefined" but when i check the vue dev tool it says that the computed property contains the array of films which doesn't really add up. The code is as follows.

   created(){
        this.fetchFilms();
    },

    methods:{

        fetchFilms(page_url){
            let vm = this;
            // storing the page url
            page_url = page_url || '/api/films'
            axios.get(page_url)
            .then(response => response)
            .then(response => {
            this.films = response.data;
            vm.makePagination(response.meta, response.links);
            })
            .catch(err => console.log(err));
        },

        makePagination(meta,links){
            let pagination = {
                current_page: this.films.meta.current_page,
                last_page: this.films.meta.last_page,
                next_page_url: this.films.links.next,
                prev_page_url: this.films.links.prev
            }

            this.pagination = pagination;
        }
    },

computed: {
    filteredFilms () {
        return this.films.data.filter((film) => {
            return film.film_name.toLowerCase().match(this.searchString.toLowerCase())
        })

},

}

This is how the data is returned

films:Object
data:Array[10]
links:Object
meta:Object

Any help is appreciated.

Upvotes: 0

Views: 1344

Answers (1)

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

You're probably accessing filteredFilms before the request is done. I don't see any code to wait for the request. You could make filteredFilms check if the data is there and return an empty list if it isn't.

Upvotes: 1

Related Questions