'Fetching data from json server in vue with axios

I would like to know is there is a way to do something like this without backend. I am calling all data from json server and displaying on home page:

    async created() {
        try{
            const products = await axios.get('http://localhost:3000/products')

            this.products = products.data
        } catch(err) {
            console.log(err)
        }
    }

Now when i click any of these products i would like to redirect user to new page and would like to display data of that specific object from json server. What i have built for now is when user click on any product he gets redirected to route /product, and everything is hardcoded there, no dynamic data. I hope my question is clear, thank you everybody.



Solution 1:[1]

You should consider using Vuex for this.

Move your method from created() to vuex's action and then call it in the hook.

The Vuex store's code is gonna be something like this:

state: {
  products: []
},
getters: {
  getProductById: (state) => (id) => state.products.find(product.id === id)
},
mutations: {
  SET_PRODUCTS(state, products) {
    state.products = products
  }
},
actions: {
  // this one is to call from the hook
  fetchProducts({ commit }) {
    return axios.get('http://localhost:3000/products').then(res => {
      commit('SET_PRODUCTS', res.data)
    })
  }
}

Then call something like this from the component you're redirecting from:

<router-link 
  :to="{
    name: 'Product', // im assuming this is the /product route's name
    params: {
      id: product.id // product.id is the id of your specific object your clicked on 
  }" 
>
  {{ product.productName }}
</router-link>

In your <Product /> component, you get the specific object by id from your Vuex store by using the getProductById() getter.

In your template:

...
<!-- the id we've passed as a route params -->
<h1>{{ getProductById($route.params.id) }}</h1>
...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ouflak