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

Tips for updating model data when integrating jQuery Data tables with ASP.NET MVC

Managing a large amount of data returned from JSON can be complex. To tackle this, I am utilizing jQuery dataTable for sorting, filtering, and pagination purposes. The functionality is working seamlessly for sorting, searching, and paginating the data. H ...

Adding text after a div in React-JS using Bootstrap: A quick guide

Just starting out with website development and I have a question. As I practice making this website, I am struggling to figure out how to add the text "To know more about us click here" below the 'Get started' button. I tried adding a simple < ...

How can I access assets in .vue files with Vapor?

My goal is to distribute assets on Cloudfront with the correct URLs upon deployment. Since I am not utilizing blade, I am unable to use the asset helper and there are no documented instructions for this situation. ...

Highcharts plots only appear once the browser window is adjusted

Having some issues while testing out the Highcharts javascript charting library on a specific page. The problem I'm encountering is that none of the data appears until I adjust the browser's size slightly. Prior to resizing, the tooltip does dis ...

Determine if a specific identifier is already present using Javascript or Jquery

Is there a way to determine if an html tag with its specific id is present more than once in the code? This is my pseudocode for checking: if($('#myId').length > 1) { // It exists twice } ...

jQuery mobile menu: Scroll to content after closing the menu

I am currently working on a project where I am using mmenu for the first time. It's functioning as expected, but there is one particular issue that I would really like to have resolved. Here is the URL: What I am hoping to achieve is that when a men ...

The process of uploading a React App to Heroku resulted in a critical error: "FATAL ERROR: Heap limit reached, Allocation failed - JavaScript heap out of memory."

There's a puzzling issue that I believe I have the solution to (paying for more bandwidth on Heroku), but the root of the problem eludes me and it's truly frustrating. Any assistance in pinpointing the cause would be greatly appreciated! Hopefull ...

How can a Vue component interact with a JavaScript method?

Within my main.js file, I have configured Vue as follows: window.Vue = require('vue'); Vue.component('my-component', require('./components/MyComponent.vue')); const app = new Vue({ el: '#app', }); Additionall ...

Exploring the capabilities of VueJs in detecting events triggered by parent components

When users click on a specific image in the Collection(parent component), my goal is to display that image in a Modal(child component). Below is the code snippet: routes.js import Home from './components/Home'; import About from './compone ...

Encountering AJAX Error 0 with jQueryUI Autocomplete upon pressing enter key

Currently, I am facing an issue with a search box that utilizes the jqueryUI .autocomplete feature to retrieve data through AJAX for providing suggestions. The problem arises when a user presses the enter key before the AJAX call to the source completes, r ...

Efficiently Passing Data Between jQuery Dialog Boxes

English is not my strong suit, so please bear with me. I am currently working on a project using Jquery Dialog and I need to display multiple dialogs one after the other (dialog1 opens dialog2 which opens dialog3...) The issue I'm facing is that when ...

Warning: Unhandled promise rejection - An error has occurred that prevents headers from being sent to the client

When attempting to retrieve a login response, I encountered the following error: (node:5904) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing. ...

What could be causing my JavaScript function to produce repeated letters with just one key press?

After implementing a code that generates different variables based on the 'truth' variable, I encountered an issue. Everything works flawlessly when 'truth' is set to "name," but as soon as I switch it to "email," any keystroke results ...

Google Locations API + React JS + Node.js data not returning

I would like to express my gratitude in advance for any assistance provided. I am currently exploring the development of an application using data from the Google Places web services API. I am utilizing AngularJS, PHP, and HTML for this project. Unfortunat ...

Using Vuex and array.findIndex but unable to locate a matching element

I am encountering an issue with the array.findIndex method. Despite being certain that there is a match in the array I am searching through, findIndex consistently returns -1. let index = state.bag.findIndex((it) => { it.id === item.id console. ...

Leveraging Deferred in conjunction with AJAX

I am facing an issue with a series of JavaScript functions that make database calls using AJAX. I need these functions to finish executing and update variables before moving on to the final function. I have attempted to use jQuery $.when but it is not work ...

The div element nested within the button is not visible

Fiddle I am trying to create a unique social button design that resembles the custom Google+ sign-in button: However, I encountered an issue where the second div element (to hold the right part of the button) is not displaying as expected: Here is the c ...

The type 'Observable<Response>' does not include a property called 'map'

I recently started learning angular and npm, but encountered an error while trying to replicate some code from a source I found (linked here). It seems like the error is related to my development environment, but I'm having trouble pinpointing the ex ...

The Jquery map function is not returning selected options, always returning empty values. It seems to be avoiding the variable, although it functions properly on jsfiddle. There are

RESOLVED: Final solution: http://jsfiddle.net/AcfUz/220/ *applied the selector mentioned in the selected answer and adjusted the console.log value to appear before the text input, where the chosen options were supposed to be displayed, and voila--it&apo ...

Issue with importing and exporting external types causing failures in Jest unit tests for Vue 2

I am in the process of creating a package that will contain various types, enums, consts, and interfaces that I frequently use across different projects. To achieve this, I have set up a main.ts file where I have consolidated all the exports and specified ...