Using Vue.js to Retrieve Data from an API and Refreshing Components When the Vuex State Changes

Coming from a jQuery background, I recently ventured into the world of Vue. Eager to learn more, I embarked on a project to create a simple user search and view details app. However, I've hit a roadblock and can't seem to find my way forward.

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

The layout consists of three components - Nav.vue, Search.vue, UserProfile.vue as shown in the image. UserProfile.vue is nested inside the router view. Utilizing Vuex store with states userId and username, along with defined mutations for state changes.

Upon user inputting a username in the Search component, the app fetches a list of users from an API on the left sidebar. Clicking on a search result triggers the commitment of userId state. Subsequently, attempting to retrieve data from the API using the userId and display the user profile on the UserProfile component within the router view.

Vuex store.js:

export default new Vuex.Store({

state: {
    userId:"",
    username: ""
}

mutations: {

setUserId (state, payload) {
    state.userId = payload
},

setUsername (state, payload) {
    state.user.username = payload
},
}

});

On Search.vue

Search.vue (outside  <router-view />)
-------------------------------------
<a href="#" @click="viewProfile" class="btn btn-info" >View Profile</a>

methods: {

viewProfile() {
this.$store.commit("setUserId", this.userId);
this.$store.commit("setUsername", this.username);
}
}

On UserProfile.vue

Accessing userId from state through a computed property.

UserProfile.vue (inside  <router-view />)
-------------------------------------------

computed: {
userId () {
return this.$store.state.userId
}
}

Need assistance in fetching and displaying data based on the selected userId retrieved from Vuex store. Any guidance would be highly appreciated. Thanks!

Answer №1

My approach would be the following:

Within the viewProfile method, I would first update the userId and username before making an API call. In this scenario, I typically utilize Vuex by placing the setUserId and setUsername mutations inside a Vuex action. The API call will require the userId as a parameter, and the response (profile data) can either be stored in Vuex or within the component.

In my opinion, there is no need to modify the URL when selecting a user from the list of search results. The UserProfile component can simply render the response data.

However, if we are required to navigate to other pages such as localhost://users/:id, then utilizing the mounted hook becomes necessary. This is where we should invoke the fetch function to retrieve the profile data based on the router parameter id.

Answer №2

Your application should have state, getters, mutations, and actions in the store. Getters are used to retrieve the current state of the application. Mutations are responsible for updating the state, and they should only be called from actions. Actions are used to trigger mutations and perform asynchronous operations.

Within actions, you can also make API calls to fetch data. To use actions, the syntax is: $store.dispatch("action-name", payload) - where the payload is optional.

For more information on Vuex and how to compose actions, please visit the following link: https://vuex.vuejs.org/guide/actions.html#composing-actions

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

What is the trick to concealing a div on a webpage through the addition of a designated parameter to the URL?

As a newbie blogger delving into the world of HTML, my knowledge of JavaScript is quite limited. I am eager to find out how I can hide any div on a webpage simply by adding a parameter to the URL; for example, if I were to add ?hide=header-wrapper at the e ...

When attempting to access Element.object3D in A-frame using TypeScript, an error stating "The 'object3D' property does not exist on the 'Element' type" is encountered

As a Japanese student, I ask for your understanding regarding my limited English proficiency. Currently, I am working on developing an a-frame library that utilizes anime.js in TypeScript to create animations. However, I encountered an issue when attemptin ...

I'm noticing that when I refresh the page, my inputs seem to disappear from the page, yet I can see that they are saved in the console's local

If anyone can help me with this issue I'm facing, I would greatly appreciate it. My aim is to retain values in the text box along with local storage even after refreshing the page. Here is an example of the code I am working with: Link to my web appl ...

Tips for displaying multiple results from a MySQL query in a single .ejs file using Node.js and Express

Currently diving into Node.js and working on a web application, I am faced with the challenge of rendering twice in the same .ejs file. Consider the scenario presented in the following .ejs file: <table> <% rows.forEach(function(ind){ %> /* m ...

Enhance the style of your React components with React-addons-css-transition

Currently, I am working on creating tabs in React JS and incorporating animations using React-addons-css-transition-group. The code snippet I have written for this purpose is as follows: render() { let view = this.state.tiresView ? this.renderTiresV ...

Stepper wizard experiences a variation in CSS styling when minified

Two plunkers showcasing material design wizard selectors are causing different behavior upon stepper clicks. One uses a minified version of CSS while the other is expanded. The issue arises with the transition effects in the .step-wizard .progressbar class ...

Converting CSS code into JavaScript

I am currently working with the following code: .mr15 > * margin-right: 15px &:last-child margin-right: 0 I need help translating this code to Javascript. Should I use JQuery or pure Javascript for this scenario? Thank you. ...

While validating in my Angular application, I encountered an error stating that no index signature with a parameter of type 'string' was found on type 'AbstractControl[]'

While trying to validate my Angular application, I encountered the following error: src/app/register/register.component.ts:45:39 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used ...

The text loader feature in THREE.js is failing to load

My first attempt at coding THREE.js resulted in a black screen when I tried to load the Text loader. Can someone help me resolve this issue? I kept getting the following error even after multiple attempts: three.module.js:38595 GET 404 (Not Found) ...

Using Node, Express, and Swig Template to incorporate variables within HTML attributes

I have been utilizing as the template engine for my Node/Express application. Although I am able to pass data into the template successfully, I am encountering difficulties when trying to use variables. My code snippet looks like this: {% for person in ...

The JavaScript popup is not functioning properly when using a comparison operator

There are 5 links with mini preview photos and URLs. Out of the 3 links, two are considered good while the other two are not. Clicking on a good link takes me to a new page, but clicking on an error link changes the href attribute to addressError, triggeri ...

Container for Magazines using HTML and CSS

Looking to develop a digital magazine application with smooth swipe transitions and fade in effects when swiping left and right. I attempted using jQuery.mobile, but struggled with adapting the background image height. My goal is to create a universal web ...

Is it possible for me to bring in/need the Kik.js document instead of using the Kik Card?

Currently working on a mobile web app designed for Kik. Their documentation advises including the Kik.js file directly in your HTML like this: <!-- simply include this script in your webpage --> <script src="http://cdn.kik.com/kik/2.3.6/kik.js"&g ...

Showing options in a menu to choose from

I'm currently working on implementing a dropdown menu for a news website. When the user selects '1' from the dropdown list, the page should display content corresponding to that selection. If the user selects '2', the page ...

Retrieve the Vue object nested within another object and log it in the console

I have a variable called 'file' in my Vue application. When I use console.log to inspect its contents, it displays as shown in the image below: console.log(file); https://i.sstatic.net/Zr2KL.png However, when I attempt to view the contents of ...

Does the onwheel event get triggered when scrolling on a trackpad?

Despite being a fundamental inquiry, the answer remains elusive to me. Due to its simplistic nature, there isn't much of an elaborate explanation available. Regrettably, I am lacking access to a laptop for testing purposes. ele.onwheel = function(e) ...

Obtaining the sub-domain on a Next.js page

Looking at my pages/index.tsx file in Next.js, the code structure is as follows: import { ApolloProvider } from "@apollo/react-hooks" import Client from "../db" import Header from "../components/Header" export default function Index() { return <A ...

Accessing data from an API in an AngularJS dropdown menu

After retrieving JSON data from an API, I store it in $scope.industry. $scope.industry = []; $http.get('/industrygroup?languageid=1') .then(function (result) { $scope.industry = result.data; }); The JSON data st ...

Tips for integrating Material UI Drawer with Redux

I have been attempting to incorporate a Drawer feature that displays on the left side while utilizing Redux to maintain the state of the Drawer. Unfortunately, I seem to have made an error as my onClick events are not responsive. Here is the code: Reduce ...

Adjusting the layout based on the WordPress page template in NuxtJs

I need to change the layout based on the WordPress page template using data fetched from a REST API. API Data { "id": 47, "template": "test.php", // require vue template based on this } export default { validate ({ params }) { return !i ...