dynamically adding cards to the screen after sending a post request to database in Vuejs

Viewed 36

I want to refresh my cardData array that gets its value by a get request from the database after I send a post request the the database. I have written this saveDraft() function that upon click adds values to cardData array but I need to refresh the page or click on it twice to see the changes. Is there a way to do it dynamically without refreshing the page?

    saveDraft() {
      Api.createComment({
          // it's a post request
        })
        .then(res => {
          if (response.status == 200) {
            Api.getComments().then(res => {
              // it's a get request to update the cardData
              if (res.status === 200) {
                this.cardData = res.data;
              } else {
                // catches error
              }
            });
          } else {
            // catches error
          }
        });
    },
1 Answers

I can't exactly see how you've implemented the saveDraft() function but I'll work with what you gave!

To generally answer your question, I think it depends on what you mean by clicking on it twice or refreshing the page (i.e. 'clicking' meaning you've bound it to a user event such as @dblclick or @click?). But in Vue, you can handle dynamic events through the following:

1) Is this function in a child component? If yes, then consider using v-on directive to listen to user events (i.e. @dblclick, @click, @mouseover, etc.), emitting a custom event, or creating a watcher that 'updates' the data in a parent.

  • If this is confusing, you can check out the video by Vue Mastery on event handling that goes over the foundations of emitting events from the child component to the parent.

2) You can consider using Vuex as a state-manager. This can help with reactivity - of updating a component or piece of data being passed around through mutations and actions. Check out a general overview of Vuex and reactivity in Vue on Vue Mastery

If this still doesn't make sense, let me know here or update your question if needed :)

Related