What is the best way to refresh a single component in my application without causing the other components to reload?

I've been working on a review application with Vue.js that fetches random facts from an API (https://uselessfacts.jsph.pl/random.json?language=en) and allows users to provide feedback through radio buttons and text inputs. Once submitted, the feedback is displayed in a list under the form. However, I'm facing an issue where the page reloads by default after submission, causing the user input to be lost.

To prevent this, I tried adding 'prevent' to the HTML form tag like this:

<form v-on:submit.prevent="handleSubmit">
but it created another problem - without reloading the page, a new fact cannot be retrieved from the API.

The setup of my two Vue components is as follows:

//first component
<template>
<div v-if="randomFact">
    <h3><span>Random fact: </span>{{this.randomFact.text}}</h3>
    <form v-on:submit='handleSubmit'>
        <input type="radio" name="reaction" id="positive" value="positive" v-model="reaction"> 
        <label for="positive">Positive</label><br>
        <input type="radio" name="reaction" id="neutral" value="neutral" v-model="reaction">
        <label for="neutral">Neutral</label><br>
        <input type="radio" name="reaction" id="negative" value="negative" v-model="reaction">
        <label for="negative">Negative</label><br>
        <br>
        <label for="feedback">Feedback</label>
        <br>
        <textarea rows="4" cols="50" name="feedback" v-model="feedback"></textarea>
        <br>
        <input type="submit" value="Submit">
        <br>
    </form>
</div>
</template>

<script>
import { eventBus } from '../main.js';
import Review from '../classes/review.js';

export default {
    name: "review-detail",
    data(){
        return {
            randomFact:"",
            reaction: "",
            feedback:""
        }
    },
    mounted(){
        fetch('https://uselessfacts.jsph.pl/random.json?language=en').then(response=> response.json())
       .then(randomFact=> this.randomFact= randomFact)
       .catch(error=> console.log(error))
    },
    methods: {
        handleSubmit(){
            let review = new Review(this.randomFact.text, this.reaction, this.feedback);
            eventBus.$emit('review-recorded', review)
        }
    } 
}
</script>

//second component
<template>
    <div>
        <ul id="reviews" v-bind="reviews">
            <li v-for="review in reviews" :key="review.reaction">
                <p>Random fact: {{review.randomFact}}</p>
                <p>Reaction: {{review.reaction}}</p>
                <p>Feedback: {{review.feedback}}</p>
            </li>
        </ul>
    </div>
</template>

<script>
import { eventBus } from '../main.js';
import Review from '../classes/review.js';

export default {
    name:'reviews-list',
    data(){
        return{
            reviews:[],
        }
    },
    mounted(){
        eventBus.$on('review-recorded', (review)=>{
            this.reviews.push(review);
        })
    }
}
</script>

I need to figure out how to reload the first component to get new facts from the API without refreshing the second component. Am I handling the communication between these two components incorrectly in my Vue app? My goal is to save user input from the first component and display it in the second component while updating the first component with new random facts.

Answer №1

To prevent the form from being submitted by the browser, make sure to include

<form v-on:submit.prevent="handleSubmit">
in your code.

When implementing the handleSubmit method, remember to utilize a background HTTP request to communicate with your API. Consider using a popular solution like Axios.

There are various libraries available for this task, but Axios is recommended due to its widespread usage and availability of tutorials and support. While you could use standard XMLHttpRequest, it may not be the most optimal choice for Vue.js projects.

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

When scrolling, use the .scrollTop() function which includes a conditional statement that

As a newcomer to jQuery, I've been making progress but have hit a roadblock with this code: $(window).scroll(function(){ var $header = $('#header'); var $st = $(this).scrollTop(); console.log($st); if ($st < 250) { ...

After updating to Angular 7, an error was encountered: "TypeError: Unable to execute map function on ctorParameters"

After updating my Angular project to version 7, I encountered a new issue. When running "ng serve --open" from the CLI, I received the following error message: Uncaught TypeError: ctorParameters.map is not a function at ReflectionCapabilities._own ...

Identify and sort JSON objects based on keys with multiple values

My JSON file contains objects structured like this: [ { "name" : "something", "brand": "x", "category" : "cars" }, { "name" : "something2 ...

Unlock the Power of TWBS Ratchet: Manually Closing Modal Windows

Currently, I am in the process of developing a mobile web application using Ratchet. The main task at hand involves opening a modal, filling out a form, clicking a button to save the input data, and then closing the modal. Although I have managed to close ...

Stop JavaScript Injection Attacks

Let's consider a scenario where a user inputs information into a form that is then submitted to the server using PHP. In the PHP code, we have: $data = $_POST['data']; // or $data = strip_tags(@$_POST['data']); I am curious t ...

The Vue component should trigger the display of data in a Bootstrap modal based on the row of the button that was

Here is a sample code snippet demonstrating how data is fetched from the database: <table class="table table-bordered"> <thead> <tr><th>User ID</th><th>Account Number</th><th>Accou ...

Using Javascript to create a radio button group

Is there a way to trigger an alert message when all radio buttons are checked as 'no'? I currently am only able to check each radio button individually. //The method I currently know $('#attraction1').change( function(){ if ($(this ...

Prevent global CSS from being overridden in a production environment for a React Next.js application

Being new to REACT-NEXT and coming from an Angular background, I am struggling with fixing this issue. Here is the element I am using from another resource: import example-custom-ele-parent, {example-custom-ele-child} from 'custom-tags/example-custom& ...

Turning a lambda function into a function that is compatible with next.js API: A step-by-step guide

I am currently using an Instagram API to retrieve data from my personal profile, which is triggered by a lambda function on Netlify. Here is a snippet of the code: require('isomorphic-unfetch') const url = `https://www.instagram.com/graphql/quer ...

What is the best way to connect to a SPA address?

I have a Vue application with a single page that uses hash history for the URLs, such as . Another website built using Wagtail CMS is trying to link to my Vue single page app using an anchor tag but it doesn't seem to be working. The site with the anc ...

After the jquery.show function is executed, an unexpected WebDriverException occurred, indicating an unknown error that prevents focusing

Here is my line of JavaScript code: $('#name').show(); And this is my webdriver code line: wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("name"))).sendKeys("Some Name"); When running the test, I encountered an exception: Web ...

What is the best way to retrieve a value from an object using a promise after a certain period of time

During an event, I receive a user object. When I try to access the user._properties.uid value before using setTimeout, it returns as undefined. However, when I implement setTimeout, the value is successfully fetched after a few seconds. Is there a way to ...

What methods are commonly suggested for managing internationalization in Vue.js applications?

Transitioning from Django to vue.js has been a challenge for me, especially when it comes to dealing with translations. In Django, the workflow for adding translations felt intuitive and fool-proof: Annotate code with translation hooks. Pull out translati ...

Execute a Google Analytics Request within a Chrome Extension Background Script

Here's a code snippet that I'm working on. It's supposed to send a daily "order" to Google Analytics to track the number of daily uses installed. I've set the interval for testing purposes to 5 seconds, but it doesn't seem to be wo ...

Tips for customizing the time selector in material-ui-time-picker

Is there a way to enable keyboard input control for the material-ui-time-picker? Currently, it only allows editing when clicking on the clock interface. Here is a snippet of my code: import React, { Component } from "react"; import { TimePicker } from " ...

Using Lodash to Substitute a Value in an Array of Objects

Looking to update the values in an array of objects, specifically the created_at field with months like 'jan', 'Feb', etc.? One way is to loop through using map as demonstrated below. However, I'm curious if there's a more co ...

Attempting to showcase extensive content based on the selection made in a drop-down menu

As a newcomer to anything beyond basic HTML, I am seeking guidance and assistance (preferably explained at a beginner level) for the following issue. If I have overlooked any crucial rules or concepts in my query, I apologize. I aim to have each selection ...

What is causing the error message "generator function required" to appear on my screen?

I recently installed the npm module called "koa-cache-control" and inserted the following code lines into my index.js file. const cacheControl = require('koa-cache-control'); After that... app.use(cacheControl({ noCache: true })); Upon sta ...

Populate Jquery datatables programmatically

After implementing the Jquery Datatables plugin, I initially had hardcoded content in the table. However, I made some modifications to dynamically populate the table with fetched data. While this change worked fine, I encountered issues with the search f ...

Passing image source from parent component to child component in Vue.js

I encountered an issue where I stored the image file name in a variable within the parent component and passed it to the child component using props. However, despite this setup, the child element is not displaying the image as expected. Here is the data ...