passing user ID between components with the help of Vue Router

I have a list of users retrieved from an API. I want to ensure that when you click on a user's name, it opens a separate page with their information and a unique link.

UsersList Component

<button @click="showUserPage(user.id)">Go to the user's page</button>
data() {
  return {
    users: [] 
  }
}
showUserPage(userId) {
  // Navigate to user details
  this.$router.push({ name: 'user-page', params: { userId: userId } })
}
fetchUsers() {
  axios.get('https://jsonplaceholder.typicode.com/users/')
      .then(response => {
        this.users = response.data;
      })
      .catch(error => {
          console.error('Error loading users', error);
      });

UserPage Component

data(){
    return{
      user: {}, 
 
    }
  },
methods:{
  getUser(userId) {
    axios.get(`https://jsonplaceholder.typicode.com/users?userId=${userId}`)
        .then(response => {
          this.user = response.data;
        })
        .catch(error => {
          console.error('Error loading users', error);
        });
  }
created() {
  this.getUser(this.$route.params.userId)

router.js

const routes = [
    { path: '/', component: UserList },
    { path: '/user/:userId',name:'user-page', component: UserPage }
]

Upon clicking the button, a link with the correct ID will appear (e.g., 'http://localhost:8080/#/user/8'). However, when attempting to display user information using {{user.name}}, I encounter an error 'Uncaught ReferenceError: user is not defined'. Additionally, trying to log this.$route.params.userId results in an error "cannot read properties of null (reading '$route'). What am I missing?

Answer №1

It appears that your template is trying to display the user object before receiving a response from the API.

To address this, consider using a v-if directive to prevent Vue from rendering the data prematurely.

You could modify your code like so:

<div v-if="user">
    Hello, {{ user.firstName }}
</div>

For added functionality, you might want to include a loading indicator for better user experience.

Here's an example script snippet with a loading indicator:

<script>

    ...
    data() {
        return { 
            userIsLoading: false,
            user: undefined,
        }
    } 
    methods: {
        getUser(userId) {
            this.userIsLoading = true;

            axios.get(`https://jsonplaceholder.typicode.com/users?userId=${userId}`)
        .then(response => {
          this.user = response.data;
        })
        .catch(error => {
          console.error('Error loading users', error);
        });
        
        this.userIsLoading = false;
    }

    ...
}
</script>

In your template, you can implement the loading indicator like this:

<div v-if="userIsLoading">
    Loading user information...
</div>

<div v-if="!userIsLoading && user">
    Hello, {{ user.firstName }}
</div>

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

Issue with the usage of section helpers in express-handlebars

I'm having trouble getting the section helper to function correctly. The content of login.hbs was parsed properly, but the js section was not parsed at all. I attempted using helpers within res.render() and directly including section() in engine(), bu ...

What is the process for updating JSON using TextFields?

I am currently facing an issue with my TextFields displayed within a material-ui dialog. These TextFields are initially populated by JSON data, which you can see in the example below. The problem is that once the TextFields are populated, I am unable to up ...

Displaying a PHP variable within Leaflet.js on an OpenStreetMap using JavaScript

I am currently working on integrating an openstreetmaps set to a specific latitude and longitude using leafletjs. For the custom fields from the backend, I am retrieving them like this : $longitude = the_field('longitude','option'); $ ...

What is the process for altering an SVG image following a click event in Javascript?

I have a tab within a div that includes text and an svg icon as shown herehttps://i.stack.imgur.com/TjwIK.png When I click on the tab, it expands like this https://i.stack.imgur.com/XNuBi.png After expanding, I want the svg icon to change to something e ...

Renew the php blade foreach loop using jQuery to update data live

I have a foreach cycle in my HTML, and at one point, some data is posted from JavaScript. I would like to append it once it is added to the database. I need to find a way to refresh the foreach loop without reloading the entire page (I could simply use ap ...

React Native query: What could be causing the inability to pass parameters (props) to my screen when utilizing stack navigator?

App.js const Stack = createNativeStackNavigator(); export default function App() { return ( <Provider store={store}> <NavigationContainer> <Stack.Navigator initialRouteName="Main"> <Stack.Screen ...

What are the drawbacks of misusing await as a return statement?

Discovering a unique approach to writing linear code with promises in Javascript, I found the following intriguing but somewhat unconventional method: const return_by_death = new Promise((resolve) => {}); Additionally, const signup = async (req, res) = ...

The method of iterating over a string in key-value pairs

How can I efficiently loop through a string and extract key/value pairs? The data is provided to me as a single string using the jstorage plugin. I attempted to split the string into an array, but the resulting key/values were not as expected. For exampl ...

Utilizing React's useState with array.map for handling multiple elements

I want to create multiple useStates for dynamically generated elements within an array.map. Each element in the array.map should share the same useState but have a unique assigned value. For instance, if the array.map contains three different elements, e ...

Set up local package dependencies using npm

My current situation involves having an npm dependency installed from a local path, which also has its own dependencies. I have observed that in this scenario, npm simply copies the contents of the local folder into node_modules. Is there any possible wa ...

Utilizing the v-for directive to loop through JSON data with unique IDs and linking them to Input components in PrimeVue

In my database, I have a collection of products with a column named attributes that stores property/value pairs in JSON format. Each product can have unique attributes. For instance, one product's attributes could be: #product1 attributes { color: & ...

Troubleshooting when a page fails to display after navigating in React

Currently, I am in the process of learning React. One of my projects involves building a page called App.js which serves as a Login Page. I have successfully navigated to another page named App2.js. However, upon navigating, I encountered an issue where th ...

AngularJS - how to dynamically delete a directive from an element

Looking for a way to dynamically add or remove directives from compiled and linked elements? I have a page with numerous inputs and want to disable all of them if a specific flag is set. The conventional method using jQuery's element.prop('disabl ...

Guide to adjusting the color of Fluent UI icon when hovering with mouse?

I've been implementing Fluent UI in my current project. When initializing my button, I use this straightforward JavaScript code: iconProps: { iconName: 'NewFolder', styles: { root: { color: 'orang ...

What is the process for uploading a single file and an array of files with varying names using multer?

I am having trouble figuring out how to upload a main image and side images from 2 different file inputs using multer. It seems that multer only accepts one upload per route. How can I work around this issue? I keep getting an unexpected field error when a ...

Custom pagination for next/previous links in Django REST framework

When it comes to backend operations, I have integrated the PageNumberPagination as the DEFAULT_PAGINATION_CLASS. Since I am utilizing vue.js along with fetch, there is no need for me to include the entire URL structure provided by django-rest-framework: " ...

Creating a Bottom-Up Menu in React Native: A Step-By-Step Guide

Need help figuring out how to create a menu that pops up from the bottom when a button is clicked. Any advice on where to start? If you have any guidance or insights, they would be highly appreciated. ...

Creating an HTML button that will execute JavaScript code when clicked

My goal is to create a button that, when clicked, updates the background of another div. These buttons are dynamically generated using PHP from images in a folder. <!DOCTYPE html> <html> <head> <meta charset="UTF-8> <scr ...

Replace jQuery CSS with standard CSS without using !important to override styles

Recently, I encountered a puzzling situation: I have an element with the following CSS properties ($(this) represents the cloned object): clone.css({ 'width': $(this).width() + 'px', 'height': $(this).height() + ' ...

Changing an array in JavaScript within a function

When working with arrays in JavaScript, how can I mutate the value of an array inside a function? I'm aware that certain array methods can achieve this, but regular assignment doesn't seem to work. var arr = [4]; function changeArray(arr) { ...