How can you showcase the content of an object within an array?

I am currently working on a project component that involves retrieving and logging data. However, I am facing an issue with accessing objects within my array of clients to display them properly in my table.

Here is the script I am using:

<script>
export default {
  data: () => ({
    clients: [],
  }),

  methods: {
    getClients() {
      this.$api
        .get("/api_v1/clientes", {
        })
        .then((response) => {
          this.clients = response.data[0];
          console.log(response.data);
        })
        .catch((e) => {
          console.log(e);
        });
    },
  },

  mounted() {
    this.getClients();
  },
};
</script>

Below is the code for my table:

 <tbody>
          <tr v-for="client in clients" v-bind:key="client.id">
            <td>{{ client.id }}</td>
            <td>{{ client.name }}</td>
            <td>{{ client.email }}</td>
            <td>{{ client.documents.cpf || client.documents.cnpj }}</td>
            <td>{{ client.documents.celular }}</td>
            <td>{{ client.status }}</td>
            <td v-if="client.address">
              {{ `${client.address.localidade} / ${client.address.uf}` }}
            </td>
            <td v-else>-</td>

            <td>
              <a :href="`/see-client/${client.id}`"><i class="icon-magnifier"></i
              ></a>

              <i class="icon-check" style="color: green"></i>
              <i class="icon-close" style="color: red"></i>
            </td>
          </tr>
        </tbody>

This is the controller snippet:

  public function index(Request $request)
    {
        $data = [
            'pag' => 'All clients',
            'link' => '/'
        ];

        return view('clients.index', $data);
    }

The relevant data can be found here. If anyone has suggestions or alternative approaches utilizing Vue2, feel free to share. As this is one of my first major projects, I appreciate your understanding and any advice you may have. Thank you for your time!

Answer №1

Here is a tip on how to handle your client data:

this.clients = response.data[0];

response.data holds an array of clients. By referencing .data[0], you specifically extract the first client from the array.

However, the next step in the code attempts to iterate over a single client instead of the entire array of clients.

<tr v-for="client in clients" v-bind:key="client.id">

To solve this issue, consider modifying the assignment like so:

this.clients = response.data;

If the above solution doesn't work due to a complex data structure, try the following alternatives:

this.clients = response.data.data;

Or perhaps (if there are multiple nested data properties):

this.clients = response.data.data.data;

Answer №2

Upon reviewing your code, I believe there are some areas that could benefit from refinement.

Firstly, let's address the JavaScript section:

<script>
export default {
  data() {
    return {
      clients: [],
    };
  },

  methods: {
    async getClients() {
      try {
        const response = await this.$api.get("/api/clientes");

        this.clients = response.data.data;
      } catch (e) {
        console.log("Check this error: ", e);
      }
    },
  },

  async mounted() {
    await this.getClients();
  },
};
</script>

Next, update your API controller logic to utilize response()->json(...):

public function index(Request $request)
{
  // Your retrieve logic...

  return response()->json($data);
}

Once these changes are made, ensure that your Vue component is able to correctly retrieve information and display it within the tbody as follows:

<tbody>
  <tr v-for="client in clients" v-bind:key="client.id">
    <td>{{ client.id }}</td>
    <td>{{ client.name }}</td>
    <td>{{ client.email }}</td>
    <td>{{ client.documents.cpf || client.documents.cnpj }}</td>
    <td>{{ client.documents.celular }}</td>
    <td>{{ client.status }}</td>
    <td v-if="client.address">
      {{ client.address.localidade }} / {{ client.address.uf }}
    </td>
    <td v-else>
      -
    </td>

    <td>
      <a :href="`/see-client/${client.id}`">
        <i class="icon-magnifier"></i>
      </a>

      <i class="icon-check" style="color: green"></i>
      <i class="icon-close" style="color: red"></i>
    </td>
  </tr>
</tbody>

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

Creating an illustration with HTML5 from an image

Is it possible to draw on an image by placing a canvas on top of it? I am familiar with drawing on a canvas, but I am facing an issue where clicking on the image does not trigger the canvas for drawing. How can I resolve this? This is how my HTML looks: ...

Redux: utilizing yield within an unrecognized function

Hey there! I am brand new to Reudx-Saga and have been experimenting with it for the past few days. I feel pretty comfortable with generators, actions, redux-stores, sagas, and other concepts. Overall, I have a good amount of experience with JavaScript. C ...

Restrict direct access to Laravel API to only be accessible from the frontend

In my straightforward web project, the backend utilizes a Laravel API while the frontend is built with React. Users can interact with the application by visiting https://example.com and sending requests to . As a result, only requests originating from the ...

Utilize AJAX to fetch and display the response from a Node JS route directly onto an HTML page

At the moment, I am retrieving client-side HTML/JS inputs (var1 and var2) which are then sent to server-side Node JS. The input values are stored in variables through an AJAX post call made to a specific route. What I want now is to define the values of v ...

Can someone provide guidance on utilizing the index correctly within this v-for to prevent any potential errors?

I am encountering an issue with using index in a v-for loop to implement a function that deletes items from an array. The linter is flagging "index is defined but never used" as an error. I am following the instructions provided in a tutorial, but I am un ...

Is it necessary to alter the number of rows or columns in the table?

I'm having an issue with my code where the table is not changing the number of rows based on the selected input option. It seems to only read the first value of the select id and does not update the rows accordingly. Can someone help me identify the m ...

Steps to retrieve a rejected object with an error stored in it in the following .then() function

Within my chain of promises, there is a specific promise that needs to log an error but pass the remaining data to the next .then() const parseQuery = (movies) => { return new Promise((resolve, reject) => { const queries = Object.keys( ...

Tips for concealing JavaScript code while inspecting elements with AngularJS

Is it possible to display minified JavaScript code when using Angular and inspecting elements? ...

Transform the Material UI grid orientation to horizontal row for content display

I'm just starting out with material UI and I've put together a grid that includes two components - an autocomplete and a button. Right now, they're stacked on top of each other, but I want to align them side by side in a row. Here's the ...

I am interested in creating an input range slider using React and TypeScript

This code was used to create a slider functionality import { mainModule } from 'process'; import React, { useState } from 'react'; import styled from 'styled-components'; const DragScaleBar = () => { const [value, setV ...

Deactivate a function within Bootstrap JavaScript

Is there a way to temporarily disable a function within Bootstrap after a click event? <a href="#"><span class="glyphicon glyphicon-triangle-right" id="btn04" onclick="myfun();"></span></a> Additionally, I am looking for a soluti ...

"Utilize Regular Expressions to conceal part of a text string with a

Looking for a way to conceal part of a string using JavaScript? For example, wanting to mask the second and third segments of a credit card number like this using regex: 4567 6365 7987 3783 → 4567 **** **** 3783 3457 732837 82372 → 3457 ****** 82372 ...

When I attempt to navigate using a route on my website, all I see is a

Hey everyone, I'm looking to develop a webpage that switches pages using Navbars. I want to utilize bootstrap and react-route-dom to achieve this functionality. However, before incorporating bootstrap, I encountered some errors that went unnoticed. I& ...

Performing a JavaScript Axios POST request following a series of iterations using a while loop with

Just getting started with async/await and feeling a bit lost. I'm trying to figure out how to send an axios post request after a while loop finishes. Is there a way to wrap the while loop in an async function and await for it? Here's the code s ...

Avoiding Memory Leaks and Managing JS Heap Size While Polling Large Amounts of Data Every 5 Seconds with Vuex

I'm currently working on a Vue application that utilizes Vuex for state management. Within this application, I have several store modules set up at the root level. Periodically, every 5 seconds, I retrieve a large amount of data and update the store s ...

The difference between invoking a method directly and utilizing a function to invoke a method

Imagine we have a method inside a class that looks like this class Blog extends Component { postClicked = (id) => { this.setState({selectedPostId: id}) } render () { const newPosts = this.state.posts.map(el => { return & ...

using the newquestion variable later in the function

In the Vue.js code snippet below, there is a variable named newQuestion that is passed to the function getAnswer like this: this.getAnswer(newQuestion). Further down in the methods section, particularly at this line getAnswer: _.debounce(, I would like to ...

Using async and await for uploading images

I am trying to create a post and upload an image if one is provided. If I successfully upload the image, everything works smoothly. However, if I do not upload an image, I encounter the following error: UnhandledPromiseRejectionWarning: TypeError: Cannot r ...

What methods can be used to send JSON data in the body of an express router.get request?

I am currently working on setting up an express endpoint to fetch data from an API and return the JSON response in the body. We are receiving JSON data from a rest API as an array and my goal is to utilize express router.get to present this formatted JSON ...

Apply a chosen style to the element that was clicked on, while removing the style from the rest

Here is an example of my ul li structure: <div id="categoryTree"> <ul> <li id="cat_15"> <a class="hasSubCat" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">N ...