My website has a dynamic list feature where users can input text to create new projects. The program sends an HTTP request when the page is loaded for the first time to retrieve all projects for the current user and display them on the screen. Users can also add new projects, but they are not immediately shown on the page without refreshing.
The JavaScript code for this functionality is:
export default {
name: "Projects",
data: function() {
return {
Projects: [],
ProjectName:'',
Username:''
}
},
created(){
this.GetAllProjects();
},
methods: {
CreateNewProject: function() {
var app = this; var idNo = XXXXX; var username= XXXXX;
axios({
method: "post",
timeout: 3000,
headers: {
.......
},
url: "XXXXXXX", data: {
name: app.ProjectName,
username: username,
}
})
.then(function(response) {
console.log(response);
app.ProjectName = "";
})
.catch(function(error) {
console.log(error);
});
},
GetAllProjects: function(){
var app = this; app.id = XXXX; app.Username= XXXX;
const instance = axios.create({
timeout: 3000,
headers: {
......
}
});
instance.get("XXXXX")
.then( function(response) {
console.log(response);
Object.keys(response.data.result).forEach( function (product) {
console.log(response.data.result[product]);
console.log('product number: ' + product);
var subscribersCounter = 0;
let example = {
name: response.data.result[product].name,
id: response.data.result[product].id,
subscribers: response.data.result[product].subscribers,
products: response.data.result[product].products,
};
let uploadedExample = {
name: '',
id: '',
subscribers: '',
products: {name:'',color:''},
};
uploadedExample.name = example.name;
uploadedExample.id = example.id;
if ( example.subscribers ) {
Object.keys(example.subscribers).forEach(function (key) {
subscribersCounter++;
});
}
uploadedExample.subscribers = subscribersCounter;
if ( example.products ) {
Object.keys(example.products).forEach(function (Pkeys) {
uploadedExample.products.name = Pkeys;
Object.keys(example.products[Pkeys]).forEach(function (key) {
if (key == 'color') {
uploadedExample.products.color = example.products[Pkeys][key];
}
});
});
}
app.Projects.push(uploadedExample);
});
})
.catch(function(error) {
console.log(error);
});
}
}
}
In the template section:
<b-col v-for="(project,index) in Projects" :key="index">
<b-row><h1> {{project.name}} </h1></b-row>
..........
Solution Attempted:
While the initial load correctly fetches and displays all projects for the user, adding a new project does not update the list on the screen dynamically. Refreshing the page with location.reload();
was attempted but did not provide the desired outcome.
Note: Simply updating the array of projects will not suffice as I require the additional data obtained from the HTTP request for processing purposes.