Updating Vue 3 asynchronous data doesn't reflect changes when the local settings are modified

I have a dedicated external .js file designed to retrieve data from the backend depending on the website's locale. Check out the code snippet below:

import { ref } from "vue";

export function fetchData(section, key) {
  // Making a GET request using fetch with error handling and headers
  const headers = {
    method: "GET",
    headers: { "Content-Type": "application/json" },
  };
  const fetchedData = ref(null);

  fetch(
    "http://localhost:4000/api/" + section + "/?api-key=" + key,
    headers
  )
    .then(async (response) => {
      const data = await response.json();

      // Checking for error response
      if (!response.ok) {
        // Retrieving error message from body or defaulting to response statusText
        const error = (data && data.message) || response.statusText;

        return Promise.reject(error);
      }

      fetchedData.value = data;
    })
    .catch((error) => {
      console.error("There was an error!", error);

      return error;
    });

  return fetchedData;
}

This is how I'm calling the fetchData function in my .vue file:

<script setup>
import { fetchData } from "../../utils/universal-fetch";
import { ref, watch } from "vue";
import { useStore } from "../../stores/language.js";
import { useI18n } from "vue-i18n";
import AOS from "aos";

const store = useStore();
const { locale } = useI18n({ useScope: "global" });

const fetchedData = ref(fetchData("homeFirstSection", store.getLanguage));

AOS.init();

watch(
  () => locale.value,
  () => {
    fetchedData.value = fetchData("homeFirstSection", store.getLanguage);
  }
);
</script>

Upon creating/refreshing the page, the fetchData function successfully retrieves data from the backend. My current challenge is updating the fetchedData variable based on the selected locale when it changes.

Problem

Thank you!

Answer №1

Encountered an issue. See the code below:

export function async fetchData(section, key) { // Added async
  // Performing a GET request using fetch with error handling and headers
  const headers = {
    method: "GET",
    headers: { "Content-Type": "application/json" },
  };
  let fetchedData = null;

  await fetch( // Added await
    "http://localhost:4000/api/" + section + "/?api-key=" + key,
    headers
  )
    .then(async (response) => {
      const data = await response.json();

      // Checking for error response
      if (!response.ok) {
        // Retrieving error message from body or default to response statusText
        const error = (data && data.message) || response.statusText;

        return Promise.reject(error);
      }

      fetchedData = data;
    })
    .catch((error) => {
      console.error("An error occurred!", error);

      return error;
    });

  return fetchedData;
}

In my external .js file, I discovered that one more async await was required.

<script setup>
import { fetchData } from "../../utils/universal-fetch";
import { ref, watch } from "vue";
import { useStore } from "../../stores/language.js";
import { useI18n } from "vue-i18n";
import AOS from "aos";

const store = useStore();
const { locale } = useI18n({ useScope: "global" });

const fetchedData = ref(null);

fetchData("agreementsFirstSection", store.getLanguage).then(
  (data) => (fetchedData.value = data)
); // Added .then

AOS.init();

watch(
  () => locale.value,
  () => {
    fetchData("agreementsFirstSection", store.getLanguage).then(
  (data) => (fetchedData.value = data)
); // Added .then instead of directly assigning
  }
);
</script>

In the .vue file, I realized that '.then' was missing instead of directly assigning the value to a variable. Comments were added to compare changes before and after.

Issue resolved

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

Challenge with Expect.js validation in a lesson on Codeacademy

I am currently developing a lesson on Codecademy to teach users about the construction of HTML forms. This project is mainly for my own enjoyment, just to keep everyone in the loop. After reviewing the submission test guidelines and API, I made the decisio ...

Error Uploading File to Cloudinary Platform

I am currently developing a REST API using Express.js. The main functionality of the API involves accepting a video file from the client and uploading it to Cloudinary. Interestingly, when I test the API by returning the file back to the client, everything ...

Configuring Visual Studio Publish settings for Single Page Applications deployed on Azure

I have set up my Azure App Service and downloaded the publish profile settings to use FTP for publishing my single page app to Azure. However, I am interested in configuring this process in Visual Studio similar to how one would publish a .Net application ...

AJAX requests sent from different origins to AWS S3 may encounter CORS errors on occasion

My current objective is to access publicly available files stored in S3. The CORS configuration for my S3 setup is as follows: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> < ...

Vue Issue - Unable to resolve 'https' dependency when importing library

Currently, I am working on a Vue project and attempting to utilize an npm package for interfacing with the retroachievements.org API in order to retrieve data. However, I have encountered an error during this process. Below is a detailed account of how I c ...

Enhance your Morris.js charts by incorporating detailed notes and annotations

Is there a way to include annotations in my morris.js charts? I couldn't find any information about this on their official website. I specifically need to add notes to certain dates. ...

Executing one specific test in Protractor using Selenium

How can I execute a single test in Protractor with Selenium? describe('Login page', function() { beforeEach(function() { browser.ignoreSynchronization = true; ptor = protractor.getInstance(); }); it('should contain navigation items&ap ...

What is the best way to conceal the header on a 404 error page?

<HeaderContainer> <Switch> <Route exact path='/counters' component={ParentCounterContainer}/> <Route exact path='/about' component={AboutContainer} /> <Route exact path='/' component={H ...

Angularjs displays an error message stating, "Unable to assign value to property that is undefined"

Whenever I try to set a property, I encounter an error message stating "cannot set property of undefined". vm.dtr1 = {}; // Could it be that I have incorrectly initialized this? vm.dtr1.date1 = {}; // Could it be that I have incorrectly initialized this ...

Steps to programmatically update Node modules:

I am looking to incorporate the use of npm update within a script. Take a look at my code snippet below: var npm = require('npm'); npm.load(function () { npm.commands.outdated({json: true}, function (err, data) { //console.log(data); npm ...

How can data be transmitted to the client using node.js?

I'm curious about how to transfer data from a node.js server to a client. Here is an example of some node.js code - var http = require('http'); var data = "data to send to client"; var server = http.createServer(function (request, respon ...

Activate the div when hovering over the span

Experiencing an issue with triggering a visible div while hovering over a span. Here is the code structure: <ul class="products"> <li> <a href="somelink"> <img src="some image"> <div class="overlay"> Some Text</div> & ...

What is the best way to invoke a function that is saved in an array of options while using setTimeout() within an AJAX callback?

Below is the pertinent code snippet: success: [ setTimeout(function () { ajax.success }, 250), //... An interesting observation I made is that I am able to invoke ajax.success from inside the success ...

Is $timeout considered a questionable hack in Angular.js development practices?

Here's a question for you: I recently encountered a situation where I needed to edit the DOM on a Leaflet Map in order to manipulate the appearance of the legend. To workaround an issue where the map wasn't generating fast enough to access the n ...

Choose a single asset from the list of values stored in the Map

I'm looking to implement something similar to the following: let myMap = new Map<string, any>(); myMap.set("aaa", {a: 1, b: 2, c:3}); myMap.set("bbb", {a: 1, b: 2, c:6}); myMap.set("ccc", {a: 1, b: 2, c:9}); let cs = myMap.values().map(x => ...

Displaying the boolean value of a list item in an input field using Vue.js

I have a collection of data from a backend that includes strings, numbers, and booleans. These values need to be shown in text fields. I am using <b-input ... /> component from bootstrap-vue for the input field. It works fine with boolean, but th ...

Utilizing Javascript's Mapping Functionality on Arrays

Here is an array that I need help with: var gdpData = {"CA": 1,"US": 2,"BF": 3,"DE": 4}; I am trying to retrieve the value associated with BF using a loop Can anyone provide guidance on how to accomplish this using either JQuery or Javascript? ...

Can anyone help me get my carousel to work properly?

I am facing a carousel problem in my personal exercise project. I have gathered HTML, CSS, and JavaScript from the internet and am attempting to integrate them all together. //Sidebar script start $(document).ready(function () { var trigger = $(&apo ...

The Jquery append function is limited to the initial ajax request, necessitating a page refresh in order to populate another div with the desired

When making an AJAX request to retrieve a JSON array, upon successful completion another AJAX request is triggered. The retrieved data is then populated into the div of a bootstrap modal using the jQuery append function. Everything functions as expected ...

Error: JSON parsing encountered an issue with token "o" at position 1 while making an ajax request

When I try to make an AJAX call, my code is set up like this: var Data = { name : $('input[name=name]').val(), email : $('input[name=email]').val(), phoneno : $('input[nam ...