2

Trying to reach article's id and fetch it. But in somewhere I do some mistakes. Because vuex returns empty object and router-link is fails.

so far, I made some something like below.

state: { article: {}, }, getters: { bringArticle(state){ return state.article; } }, mutations: { updateArticle(state, article){ state.article = article; } }, actions: { getArticle(context, id){ axios.get("/api/articles/" + id) .then((response) => { context.commit("updateArticle", response.data); console.log(response.data) }) .catch((error) => { console.log(error); }) } } 

Clearly this axios.get("/api/articles/" + id) is not working out...

by the way. I see id's data at the endpoint without a problem. Just stuck the axios part. How can I reach the id?

Route::get("/articles/{id}", "Api\ArticlesController@singleArticle"); 
3
  • are you calling dispatch('getArticle') to get the article? it should be something like this.$store.dispatch('getArticle', 1); from within a component, with 1 being the id you want to load. Commented Jun 15, 2019 at 13:38
  • You can either change your action to be getArticle(context, { id }) or change the way you call dispatch to this.$store.dispatch('getArticle', this.$route.params.id). The way you have now, your action expects a number, and is passed an object. Commented Jun 15, 2019 at 13:48
  • thank you for the comments. I figured it out and post the asnwer. @Leite Commented Jun 15, 2019 at 14:04

1 Answer 1

0

okay, it took some time to figure it out. And not sure it is the best way, but it's working now.

I set the route-link like below to go to ID.

<router-link :to="{ name: 'detail', params: { id: article.id} }"> 

then I created api.js file and export my calls.

var apiUrl = "api/articles/"; export default { getArticles: function(){ return axios.get(apiUrl); }, getArticle: function( id ){ return axios.get(apiUrl + id); }, } 

inside my store.js I changed my action commit like:

getArticle( { commit }, data ){ path.getArticle( data.id ) .then( function( response ){ commit( 'setArticle', response.data ); }) .catch( function(){ console.log(error) }); }, 

Last, I dispatch it Detail.vue

created(){ this.$store.dispatch( 'getArticle', { id: this.$route.params.id }); }, 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.