Searching for an object in Vue 3 Composition API and displaying its contents

Experiencing a challenge with my first Vue.js project, seeking assistance in resolving the issue. Upon receiving a response from my API, I retrieve a list of projects and aim to locate the one matching the ID provided in the URL parameter. A peculiar error is logged in the console when attempting to view:

TypeError: Cannot read property 'title' of undefined

Interestingly, the correct project is eventually rendered in the template.

Here's a snippet of the code:

<template>
  <div id="wrapper">
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"
      integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA=="
      crossorigin="anonymous"
    />
    <Sidebar></Sidebar>
    <div id="content">
      <Navbar></Navbar>
      <div id="headline">
        <ul>
          <li>
            <h1>Project Details</h1>
            <Popup></Popup>
          </li>
        </ul>
      </div>
      <div id="grid" class="module-grid module-grid-2">
        <div class="card">
          <div class="card-head">
            <div>
              <h3>Metadata</h3>
            </div>
            <div></div>
          </div>
          <div class="card-body">
            <ul v-if="filtered_projects != null">
              <li>
                <div class="list-info">
                  <p>Project Number: {{ filtered_projects.id }}</p>
                </div>
              </li>
              <li>
                <div class="list-info">
                  <p>Author: {{ filtered_projects.author }}</p>
                </div>
              </li>
              <li>
                <div class="list-info">
                  <p>Company: {{ filtered_projects.company }}</p>
                </div>
              </li>
              <li>
                <div class="list-info">
                  <p>
                    Created At: 
                    {{
                      new Date(filtered_projects.created_at)
                        .toLocaleString()
                        .split(",")[0]
                    }}
                  </p>
                </div>
              </li>
              <li>
                <div class="list-info">
                  <p>
                    Last Updated At: 
                    {{
                      new Date(filtered_projects.updated_at)
                        .toLocaleString()
                        .split(",")[0]
                    }}
                  </p>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <div class="card">
          <div class="card-head">
            <div>
              <h3>Project Overview</h3>
            </div>
            <div></div>
          </div>
          <div class="card-body">
            <form class="edit-form" @submit.prevent="submitProject()">
              <label for="title">Title*</label>
              <input
                v-model="filtered_projects.title"
                name="title"
                id="title"
                class="input"
                type="text"
                required
                maxlength="16"
              />
              <label for="text">Text*</label>
              <textarea
                v-model="filtered_projects.text"
                name="text"
                id="text"
                class="input"
                type="text"
                required
                rows="6"
              />
              <label for="finish">Completed</label>
              <input
                v-model="filtered_projects.finish"
                name="finish"
                id="finish"
                class="input w-auto"
                type="checkbox"
              />
              <button v-if="state.user_info.id === filtered_projects.author || state.user_info.admin === true" type="submit" class="second-btn btn">
                Update
              </button>
            </form>
             <button v-on:click="deleteProject()" v-if="state.user_info.id === filtered_projects.author || state.user_info.admin === true" class="btn delete-btn">Delete</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<!-- Remaining JavaScript script part has been removed for brevity -->

Seeking suggestions for an improved solution. Thank you!

Answer №1

When you trigger the company_projects/getProjectList action directly within the setup function, it is possible that when your component renders for the first time, the company_projects/getProjectList getter (and subsequently the state.company_projects computed property) will return an empty array. As a result, the filtered_projects variable will be undefined (find)

This means that any part of your template that relies on filtered_projects to have a value should be wrapped in a v-if directive

<form class="edit-form" @submit.prevent="submitProject()" v-if="filtered_projects">

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

Is there a radio button that can dynamically update and modify the current view?

Although I don't consider my issue to be overly complex, as a newcomer I am struggling to find a straightforward solution. The form I have collects various items and on the output page generates a table based on this data. For instance, one question ...

Outputting messages to a component with React

I'm attempting to create a component similar to a console where messages are displayed one after the other instead of replacing the old message. My goal is to have a component where I can input strings, like in a chatbox, using different parts of my ...

What is the best way to detect a specific button press from an external component?

I need to integrate an external component written in Vue.js that contains multiple buttons. How can I specifically target and capture the click event of a particular button called firstButtonClick() within this external component? Here is how the External ...

Is it possible to dynamically update the contents of a modal body and modal footer using

I'm dealing with a modal that dynamically populates two sections: modal-body and modal-footer. However, the issue is that only the content of modal-body changes dynamically while modal-footer remains static. Here's an example of the HTML code (w ...

Unable to activate click function in Jquery

Here is a basic HTML page snippet: <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script> <script> $(document).ready(function () { $('#test').click(); }); < ...

Looking to compare two elements within different arrays? The method outlined below is specifically designed for comparing to individual values rather than entire arrays

Is this the right approach? How can we iterate through each array to compare values? Should these data structures be modified or transformed first? Below is the data that needs to be compared. The objective is to match userID with DocumentID. const videos ...

Exploring Angular 10's advanced forms: delving into three levels of nested form groups combined with

Project Link: Click here to view the project In my testForm, I have 3 levels of formGroup, with the last formGroup being an array of formGroups. I am trying to enable the price field when a checkbox is clicked. I am unsure how to access the price contro ...

How to switch around div elements using CSS

There are two unordered list items in a container div and one swap button. When the swap button is clicked, the order of items needs to change. This functionality can be achieved using the following swap function. var ints = [ "1", "2", "3", "4" ], ...

Personalizing MaterialUI's autocomplete functionality

Trying to implement the material-UI Autocomplete component in my react app and looking for a way to display a div when hovering over an option from the list, similar to what is shown in this reference image. View example If anyone has any tips or suggest ...

Text input setting for jQuery UI Slider

Currently, I am utilizing jQuery UI sliders to input values in text boxes. However, I would like this functionality to be bidirectional; meaning if a value is entered into the text box, I want the slider to move to the corresponding position. I am unsure ...

When the form is submitted, any blank inputs and their corresponding hidden fields will be disabled

I created a form that has multiple input fields, and users have the option to enter values or leave them blank. Each input field is accompanied by a hidden input field which contains a specific id unique to the corresponding visible input field. To disable ...

What is the best way to save the city name received from geolocation into a variable and then make an AJAX request?

<script> new Vue({ el: '#fad' , data: { data: {}, }, mounted() { var self = this; navigator.geolocation.getCurrentPosition(success, error); function success(position) { var GEOCO ...

Positioning Input and Dropdown Elements within a Data Table Using CSS

I am currently working on setting up a data table for an application using Vue.js, and I am facing a challenge in relation to the arrangement of input elements. The specific requirement is that certain columns within the table should contain values that ar ...

Refresh the HTML webpage using AJAX technology

I am trying to implement a simple html page with a single table that updates in the background every 5 seconds. The traditional solution of using <meta http-equiv="refresh" content="5"> is not suitable as it would disrupt the user experience by displ ...

TinyMCE generates HTML code with embedded tags

Hey there, I'm currently facing an issue with TinyMCE that I just can't seem to solve. I've browsed through some related posts but haven't found a solution that works for me... For example: When I input something in my back office, ...

Error Uploading File - Functioning in Postman but not on website interface

I'm currently pursuing the full stack certification on devchallenges.io and tackling the authentication app challenge. So far, I've successfully implemented the login and register functionality, as well as fetching the logged-in user's infor ...

Creating files for two HTML pages with Vue: A step-by-step guide

Currently, I am working on creating two HTML files as part of my project structure. This is how it looks: |- node_modules |- public | |- blog | | |- some-page.html | |- index.html |- src (contains all the Vue components) |- Blog.Vue |- Index.Vue ...

Unable to reset iframe style height in IE8 using JavaScript

I am encountering an issue with resetting the height of an iframe using JavaScript. Here is the code snippet I am working with: var urlpxExt = document.getElementById('urlPx'); urlpxExt.style.height = "200px"; While this approach works well in m ...

Issue: The variable does not appear to be getting updated

After spending the last 2 hours analyzing this JS code, I am still unable to figure out why the variable "message" is not being changed to "User already exists." The bizarre thing is that the code block labeled "Inside first if" is executed, but the "mes ...

Finding All Initial Table Cells in jQuery

Is there a streamlined method for retrieving all td elements (cells) from every row within a specific table, or do I have to manually iterate through the collection myself? ...