Category component do api call on created

Currently my category component is making http api call on its creation.

So when I go from my index to category the result of http call is efficient.

But now when I change category so I go from localhost:8080/category/1 to localhost:8080/category/2 my component isn't re-rendered so it's not created again and my http call function doesn't fire again how I would like to.

    async created() {
        try {
            console.log(this.id);
            const response = await axios.get(`/api/category/getOne.php?id=${this.id}`, axiosConfig);
            console.log(response.data.records[0].name);
            this.category = [response.data.records[0].name];

        } catch (e) {
            this.errors.push(e);
            console.log(this.errors);
        }
    } 

What do you guys suggest for me, should I place this http call not in created () but for example in methods {} and then detect if url id change and execute this function whenever it change? Or there is some better, vue approach for that?

1 answer

  • answered 2018-01-14 12:31 BT101

    I moved above code to methods {} and call it on created() and on id change like so:

    created() {
        this.getData(this.id);
    },
    watch: {
        '$route.params.id'(newId, oldId) {
            this.getData(newId);
        }
    }
    

    as @Belmin Bedak suggested in comments section.