What is the best way to find the common elements in two datasets using Nuxt?

I attempted to retrieve data from an API using parameters that are passed through an argument in a v-for loop. In the findUser function, I am able to successfully log the desired data. However, I am unable to retrieve it at the end of the findUser function; why is this happening?

I am aware that there is an asynchronous method available to retrieve the data, but I am unsure how to implement it to achieve my desired outcome. I also considered calling both APIs simultaneously, but encountered the same issue and do not know how to resolve it.

<template>
  <div>
    <h4>Received Lists</h4>
    <p v-for="element in results" id="flex-list" :key="element.list_id">
      {{ element.list_name }} from {{ findUser(element.user_id) }}
    </p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      results: '',
      nickname: '',
    }
  },
  created() {
    this.$axios
      .get(`/api/listReceived/${this.$auth.user[0].user_id}`)
      .then((res) => {
        this.results = res.data
        console.log(JSON.stringify(this.results))
      })
      .catch((err) => {
        console.error(err)
      })
  },
  methods: {
    findUser(id) {
      console.log(id)
      let data = ''
      this.$axios
        .get(`http://localhost:3000/api/userdata/${id}`)
        .then((res) => {
          data = res.data[0].nickname
          console.log(data)
        })
        .catch((err) => {
          console.error(err)
        })
      return data
    },
  },
}
</script>

Answer №1

Although my previous response veered slightly off the original question, it remains relevant. Here's a demonstration of how to properly navigate an intersection:

I opted not to use an endpoint and instead simulated local data within the data() function, which is why I kept my earlier post above.

<template>
  <div class="flex flex-col items-center">
    <h1 class="p-4 bg-green-700 rounded-md">
      List of users sorted by their respective messages
    </h1>
    <!-- <pre>{{ messages }}</pre> -->
    <section>
      <div v-for="user in groupedMessages" :key="user.id" class="mt-4">
        <p>
          User: <b>{{ user.name }}</b>
        </p>

        <aside>
          Messages:
          <span v-if="!user.messages.length">No messages yet</span>
        </aside>
        <p v-for="message in user.messages" :key="message.id">
          <span class="italic">- {{ message.text }}</span>
        </p>
      </div>
    </section>
  </div>
</template>

<script>
// ES version of lodash, lighter overall
import { cloneDeep } from 'lodash-es'

export default {
  name: 'Index',
  data() {
    return {
      messages: [
        {
          id: 1,
          text: 'Hello world',
          userId: 1,
        },
        {
          id: 2,
          text: 'Nice cool message',
          userId: 1,
        },
        // Additional message objects...
      ],
      users: [
        {
          name: 'Patrick',
          id: 1,
          messages: [],
        },
        // Additional user objects...
      ],
    }
  },
  computed: {
    groupedMessages() {
      const clonedUsers = cloneDeep(this.users)
      this.messages.forEach((message) =>
        clonedUsers.forEach((user) => {
          if (user.id === message.userId) {
            user.messages.push(message)
          }
        })
      )
      return clonedUsers
    },
  },
}
</script>

The GitHub repository is accessible here. Please disregard the unrelated repo title.

You can view the final output on Netlify.

https://i.sstatic.net/WtcXx.png

Answer №2

created() works just fine with Vue, but typically fetch() and asyncData() hooks are used in Nuxt.
Let's explore the basic concept using JSONplaceholder's API.

Below is a potential /pages/index.vue

<template>
  <div class="flex flex-col items-center">
    <h1 class="p-4 bg-green-700 rounded-md">
      List of users from JSONplaceholder
    </h1>
    <section class="mt-4">
      <p v-for="user in users" :key="user.id">
        {{ user.name }} 🚀 {{ user.email }} ~
        <nuxt-link
          :to="{ name: 'users-id', params: { id: user.id } }"
          class="border-b-4 border-green-500"
        >
          Check details
        </nuxt-link>
      </p>
    </section>
  </div>
</template>

<script>
export default {
  name: 'Index',
  data() {
    return {
      users: [],
    }
  },
  async fetch() {
    this.users = await this.$axios.$get('/users')
  },
}
</script>

<style>
* {
  @apply bg-gray-800 text-gray-100;
}
</style>

Take a look at the detailed page or /pages/users/_id.vue utilizing the fetch() hook.

<template>
  <div class="flex flex-col items-center">
    <nuxt-link class="p-4 bg-purple-700 rounded-md" :to="{ name: 'index' }">
      Go back
    </nuxt-link>

    <h2>User details ID: # {{ $route.params.id }}</h2>
    <p v-if="$fetchState.pending">Loading user's info...</p>
    <p v-else-if="$fetchState.error">Error while fetching user</p>
    <div v-else>
      <p>{{ user.name }}</p>
      <p>{{ user.phone }}</p>
      <p>{{ user.website }}</p>
      <p>{{ user.company.name }}</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserId',
  data() {
    return {
      user: {},
    }
  },
  async fetch() {
    this.user = await this.$axios.$get(`/users/${this.$route.params.id}`)
  },
}
</script>

I personally prefer this method as it doesn't block the render, and you can include a smooth skeleton to indicate ongoing activity to the user. Moreover, fetch() is available on both components and pages, whereas asyncData() is limited to pages only.
It also provides the useful $fetchState helper which can be quite handy!


Here is an example of the same /pages/users/_id.vue page using the asyncData() hook.

<template>
  <div class="flex flex-col items-center">
    <nuxt-link class="p-4 bg-purple-700 rounded-md" :to="{ name: 'index' }">
      Go back
    </nuxt-link>

    <p>{{ user.name }}</p>
    <p>{{ user.phone }}</p>
    <p>{{ user.website }}</p>
    <p>{{ user.company.name }}</p>
  </div>
</template>

<script>
export default {
  name: 'UserId',
  async asyncData({ route, $axios }) {
    const user = await $axios.$get(`/users/${route.params.id}`)
    return { user }
  },
}
</script>

The main advantage of using asyncData is its safety feature and the fact that it blocks the render (which can be seen as either a pro or a con, depending on personal preference).

For more insights comparing fetch() vs asyncData(), check out some in-depth answers.
Also, explore this informative blog article and this dev.to clone example for further understanding.


If you're considering the SSG path and aiming to optimize the process with minimal API calls once on the client-side, take a look at this response.

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

Navigating between two intervals in JavaScript requires following a few simple steps

I have created a digital clock with a button that switches the format between AM/PM system and 24-hour system. However, I am facing an issue where both formats are running simultaneously, causing the clocks to change every second. Despite trying various s ...

What is the alternative method to obtain dynamically added options without relying on the on change or onclick event?

I have a dynamic country select box where options are added on click, but I am having trouble accessing all the options in the select box with JavaScript. When I console log the select box HTML after appending the options, I only see the originally added o ...

Create dynamic elements in Vue.js components based on an object

I'm currently working on a component that will display elements within VueJs virtual dom using Vuex state. However, I have encountered an error that I am unable to comprehend and resolve: Avoid using observed data object as vnode data: {"class":"b ...

Issue with Dropzone not functioning correctly within Vue transition modal

I've implemented a dropzone function in the mounted function, which works perfectly when the dropzone is outside of a modal in the view. However, when I try to use it within a modal with a transition effect, it doesn't work. Any suggestions on ho ...

Barba.js (Pjax.js) and the power of replacing the <head> tag

I have been using barba.js to smoothly transition between pages without having to reload the entire site. If you want to see an example, take a look here. Here is a snippet of code from the example: document.addEventListener("DOMContentLoaded", func ...

Utilize VueI18n to dynamically translate JavaScript variables into different languages

Trying to show a notification based on a server returned value is my current challenge. I am uncertain about how to dynamically retrieve the translation value using the received key's value. For instance, if the error.response.data.errorDetailsCode v ...

Why is it necessary to use "new" with a Mongoose model in TypeScript?

I'm a bit confused here, but let me try to explain. When creating a new mongoose.model, I do it like this: let MyModel = moongoose.model<IMyModel>("myModel", MyModelSchema); What exactly is the difference between MyModel and let newModel = ne ...

Preserve StepContent information within Material-ui Stepper during updates to the active step

I have a Stepper component with multiple steps, each containing several TextFields. The issue is that material-ui unmounts the step contents when you switch steps, causing all the data in the TextFields to be lost. My question is: Is there a way to prese ...

Dropdown Box Linking and Input Field Integration in HTML

I have a scenario where students need to pay monthly fees for their classes. My objective is as follows: 1. Dropdown #1: Student Names 2. Dropdown #2: Month Names 3. Textbox: Fees amount for the selected month The code I am using: $(document).ready(fu ...

What is the best way to determine if any of the list items (li's) have been marked as selected?

<div id='identifier'> <ul id='list'> <li id='1' class="">a</li> <li id='2' class="">a</li> <li id='3' class="">a</li> <li id='4' class=" ...

Combining Json, Jquery Autocomplete, and PHP to customize the displayed search options based on multiple items within the Json data

I have a PHP file that returns an array of results, with the 'Name' field being one of them. I want to customize my jQuery autocomplete feature to only search by the 'Name' field and suggest results based on that. However, once a sugges ...

Displaying Two Pictures in a Carousel Item Using Vuetify

I am trying to create a carousel-item that displays two images side by side. I have attempted wrapping the carousels in row-cols and placing two images in each carousel item, but nothing seems to work. Does anyone have any suggestions on how to achieve thi ...

Pressing the button on the form has no effect

I am testing a login screen using NodeJS, but I am facing an issue where the submit button does not redirect to the dashboard screen as intended. What could be missing in the code? The submit button should direct to the dashboard screen that I have created ...

Trouble with sending data to child components via props

I've been trying to pass a prop to a child component in React, but when I check the props using console log, it doesn't show up at all. Even the key things is missing from the props. Any assistance with this would be greatly appreciated. export ...

Executing multiple child processes in a loop with asynchronous operations and collecting the output after the loop concludes

Here's a snippet of code I've been working on... const { exec } = require('child_process'); const Main = async () => { const result = await RetrieveAllItems(); console.log('output', result); }; const RetrieveAllI ...

Having trouble with Javascript's JSON.stringify or PHP's json_decode?

I am attempting to send an array from JavaScript to PHP. JavaScript: var json = JSON.stringify(extraFields); url += "&json="+json; PHP: $json = json_decode($_GET['json'], true); foreach($json as $K=>$V){ echo "json".$K . "=" . $V ...

Steps to solve React error message: "Warning: Every child in a list should have a distinct 'key' prop"

Currently, I am developing a React application that fetches movies and allows users to comment on them while also providing the option to vote/rate. Users can both comment and rate the movie they are viewing. Here is an excerpt from my code: <FormGrou ...

Guide to constructing a multi-dimensional array using dynamically generated fields and variables

Here is the URL that I wanted to share with you: All the fields visible on this page are generated dynamically from the backend. To display the pricing, I used the field names as variables in the JavaScript below. However, I encountered two issues - first ...

What is the best way to determine the exact location of a vertex in three.js?

My understanding is that var point = object.geometry.vertices[i]; will provide the relative position for the x, y, and z of the point within the object's geometry. Is there a way to obtain the absolute position if the object has been translated, rota ...

Is it normal for Node's console to not display all object properties?

After running some code, I noticed something peculiar. console.log(myURL); It seems that the extension property is missing: console.log(myURL.extension); However, when logging it on its own, the value appears correctly. The URL object was created ...