Having trouble utilizing props with Vue axios? Running into an undefined error? Unsure how to properly use props with axios?

https://i.stack.imgur.com/QfCDG.png

There seems to be an issue with my saveComment() function in CommentList.vue. It can't find the comments' post_id and causes this error:

CommentList.vue?6c27:107 Uncaught TypeError: Cannot read properties of undefined (reading 'post_id')
    at HTMLButtonElement.eval (CommentList.vue?6c27:107)
    at HTMLButtonElement.dispatch (jquery.js?1157:5430)
    at HTMLButtonElement.elemData.handle (jquery.js?1157:5234)

I'm looking for a way to use props in Vue like data, any suggestions on how I can achieve this?

  <div>
    {{ comments }}
    <button @click="getComments()" class="btn btn-primary">
      open comments
    </button>
    <!-- Button trigger modal -->
    <button
      @click="openWriteComment()"
      type="button"
      class="btn btn-primary"
      id="openModalBtn"
      data-bs-toggle="modal"
      data-bs-target="#exampleModal"
    >
      Write Comment
    </button>

    <!-- Modal -->
    <div
      class="modal fade"
      id="modalBox"
      tabindex="-1"
      aria-labelledby="exampleModalLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"
            ></button>
          </div>
          <div class="modal-body">
            <input type="text" id="commentBody" value="type your comment" />
          </div>
          <div class="modal-footer">
            <button @click="saveComment()" class="btn btn-primary" id="saveBtn">
              Save changes
            </button>
            <button
              type="button"
              class="btn btn-secondary"
              data-bs-dismiss="modal"
            >
              Close
            </button>
          </div>
        </div>
      </div>
    </div>
    <comment-item
      v-for="(comment, index) in commentlist"
      :key="index"
      :comment="comment"
    ></comment-item>
  </div>
</template>
<script>
import CommentItem from "./CommentItem.vue";
export default {
  components: { CommentItem },

  data() {
    return {
      commentlist: [],
    };
  },
  created() {
    this.getComments();
  },

  props: ["post", "loginuser", "comments"],

  methods: {
    getComments() {
      axios
        .get("/commentlist")
        .then((res) => {
          console.log(res.data);
          this.commentlist = this.comments;
          console.log(this.commentlist);
        })
        .catch((err) => {
          console.log(err);
        });

     
    },

    openWriteComment() {
      $("#openModalBtn").on("click", function () {
        $("#modalBox").modal("show");
      });
    },

    saveComment() {
      $("#saveBtn").on("click", function () {
        console.log(document.getElementById("commentBody").value);
        axios
          .post("/commentSave/" + this.comments.post_id, {
            comment: document.getElementById("commentBody").value,
          })
          .then((res) => {
            console.log(res.data);
          })
          .catch((err) => {
            console.log(err);
          });
      });
    },
  },
};
</script>

Answer №1

I believe I have found the mistake.

Mistake:

  saveComment() {
      $("#saveBtn").on("click", function () { // This callback is a regular function
        console.log(document.getElementById("commentBody").value);
        axios
            // when you get here 'this' context from Vue is lost
            // "this.comments" doesn't exist in the context of this function.
          .post("/commentSave/" + this.comments.post_id, {
            comment: document.getElementById("commentBody").value,
          })

Solution:

saveComment() {
      $('#saveBtn').on('click',  () => { // convert this to arrow function.
        console.log(document.getElementById('commentBody').value)
        axios
          .post('/commentSave/' + this.comments.post_id, {
            comment: document.getElementById('commentBody').value
          })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Need help figuring out how to use Javascript:void(0) to click a button in Selenium?

Struggling with finding the right solution, I have attempted various methods. Apologies for any formatting errors, but the element that requires clicking is: <button href="javascript:void(0)" id="payNewBeneficiary" class="button-new-payee"> ...

Spinning a CSS object around an axis

Trying to add a unique touch to my image rotation with CSS. While familiar with rotating around x, y, and z axis, I want to achieve a diagonal rotation this time. Wondering if there's a way to tweak the y axis for a more slanted effect on my image? ...

Regular Expression: do not include comments that are placed inside quotation marks

Using the regular expression /#(.*?)\r?\n|#(.*?)$/g, I was able to parse the following content. However, it also matches the comment within the quotes. How can I prevent this from happening? # # this is a comment # but this is '# not a c ...

Is there a way for me to manipulate the RGB values of the canvas in such a manner that the Red and Green components of the gradient are determined by dividing the position of my mouse cursor

My homework assignment requires using RGB colors where the red value is set to 0, green is the x-coordinate divided by 2, and blue is the y-coordinate divided by 2. I've been trying to control the colors on a canvas using addColorStop functions, but I ...

Display various items using only one EJS scriptlet tag

I'm currently facing a challenge with rendering two objects using EJS. I am curious to know if it is feasible to render them both within the same pair of scriptlet tags or if they need to be rendered separately? So far, I have been able to successful ...

Transmitting JSON AJAX response to populate location markers on Google Maps

When a button is clicked, an AJAX response is triggered to display JSON data based on a search query. My goal is to take the all_locations variable from the AJAX response and use it to show markers on a Google map. I'm uncertain about how to achieve t ...

Multiple occurrences of trigger events were detected when loading ajax content

In a div I have embedded a paragraph and a button as shown below: <div id="my_div"> <p>This is a paragraph</p> <button class="my_btn">Click here!</a> </div> The content within the div is dynamically loaded via ...

The jQuery toggle functionality seems to be malfunctioning

I have created a form that should toggle (hide and show) with the click of a button, but for some reason it's not working. Can someone please take a look at my code below and let me know what I'm doing wrong? $(document).ready(function () { ...

Sending an event to a component that has been rendered in Vue

I'm currently in the process of developing a custom rendered component that will execute a function when clicked on: // Creating a standard Vue component with a render function Vue.component('greeting', { methods: { sayHello(){ ...

How can I replicate the functionality of the span element using Javascript?

Using Javascript, I am able to display a paragraph without the need for HTML. By adding it to an HTML id, I can manipulate individual words within the text. My goal is to make specific words cursive while keeping the entire paragraph in its original font s ...

Tips for showing data associated with the chosen option from a dropdown list in Angular.js fetched from an API

My goal is to automatically display the coordinator's name based on the selection in a dropdown list populated with data from an API. The dropdown options are the email addresses from the JSON data below, and upon selecting a login ID, the correspondi ...

Implementing MUI createTheme within Next.js

After switching from material-UI version 4 to version 5.5.0 in my project, I encountered issues with createTheme. The colors and settings from the palette are not being applied as expected. Current versions: next: 11.0.0 react: 17.0.2 mui : 5.5.0 theme. ...

Ways to determine if the backbone.js model has been emptied

I often find myself wondering how to determine if a model has been cleared or is empty. For example, if I set the model with: model.set({name:'this is a test', id:1}); and then clear it with: model.clear(); ...

Solving the issue of refreshing HTML Canvas drawings in Vue3 using the Composition API

In my typescript code base, I have successfully created a Sudoku board by directly manipulating the DOM and utilizing an HTML Canvas element with its API. Now, I am looking to elevate my project to a full website and integrate what I have into a Vue3 proj ...

Resolving the active tab problem within Angular 2 tab components

Can anyone assist in resolving the active tab problem within an angular 2 application? Check out the Plunker link I am using JSON data to load tabs and their respective information. The JSON format is quite complex, but I have simplified it here for cla ...

Exploring the world of typed props in Vue.js 3 using TypeScript

Currently, I am attempting to add type hints to my props within a Vue 3 component using the composition API. This is my approach: <script lang="ts"> import FlashInterface from '@/interfaces/FlashInterface'; import { ref } from &a ...

What could be causing the data filter function to return nothing?

Whenever I press the messageIncompleted button, everything works fine. But when I click on the messageCompleted button, the data suddenly disappears. Any ideas on how to tackle this issue? messageIncompleted() { this.messages = this.messages.filter(m ...

Is there a potential impact on performance when utilizing local variables instead of repeatedly accessing properties?

Examining JavaScript code optimized for a performance-sensitive environment, specifically a game engine in mobile settings. Oftentimes, this code avoids using local variables and instead relies on explicit chains, such as: if (this.x.y[z].i) { this.x ...

Leveraging babel-cli on your local machine

Is it possible to utilize the babel client without the need for global installation? Instead of following this method npm install -g babel-cli I am looking to achieve the same outcome by using npm install babel-cli --save-dev ...

Embed the website onto a webpage using ajax or an iframe without any need for navigation

I have a unique challenge ahead. Imagine there are two websites, one is a web page and the other is hosted within the same domain. My goal is to load the entire second website into a div or iframe of the first web page, similar to how a free proxy browser ...