Dealing with asynchronous requests in Axios: A guide to solving the challenge

I'm working on a page named _id.vue in my Nuxt.js project:

<template>

  <div class="wrapper">

    <HeaderApp>

      <DivHeaderMenu>
      </DivHeaderMenu>

    </HeaderApp>

    <CenterContentDinamicFirmenistorieApp>
    </CenterContentDinamicFirmenistorieApp>

    <FooterApp>
    </FooterApp>

  </div>

</template>

<script>
  //company_history
  import axios from 'axios';
  import HeaderApp from '~/components/HeaderApp';
  import FooterApp from '~/components/FooterApp';
  import CenterContentDinamicFirmenistorieApp from '~/components/CenterContentDinamicFirmenistorieApp'
  import DivHeaderMenu from '~/components/DivHeaderMenu';
  import Pixelperfect from '~/components/Pixelperfect';

  export default{

  async fetch ({ store, params, redirect, app}) {
    return axios.get('http://seo-gmbh.eu/json/api_sunds.php?action=get_pages&url=company_history')
    .then((res) => {
      store.commit('company_history/init_data_for_firmenistorie', res.data);
    })
  },


  async validate({store, params, redirect}) {

    const urlData = store.state.company_history.dbFirmenstorie.dbFirmenistorieSortArrayData;
    let resultArray = false;

    for (let i = 0; i < urlData.length; i++) {
      if(params.id === urlData[i].toString()){
        return resultArray = urlData[i];
      }
    }

    if(resultArray == false){
        return redirect('/Firmenistorie');
    }
},


  head () {
    return {
      title: this.$store.state.company_history.dbFirmenstorie.dbFirmenistorieData.data.meta.title,
      meta: [
        {description: this.$store.state.company_history.dbFirmenstorie.dbFirmenistorieData.data.meta.description}
      ]
    }
  },

  components:{
    HeaderApp,
    FooterApp,
    CenterContentDinamicFirmenistorieApp,
    DivHeaderMenu,
    Pixelperfect
  },


}

</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

I encountered an issue where I receive a 404 error and get redirected when reloading the dynamic page (_id) instead of re-loading the same page without any errors. This is due to not receiving data from the store under certain circumstances.

I have tried various solutions to this synchronous problem with no success. Can anyone provide insight into resolving this issue effectively?

The Vuex repository code is quite extensive, but to aid in understanding the problem, here it is included:

export const state = () => ({
  dbFirmenstorie: {
    dbFirmenistorieData: null,
    dbFirmenistorieMaxYearData:  null,
    dbFirmenistorieMaxDetailsData:  null,
    dbFirmenistorieSortArrayData:  [],
  },
});

export const mutations = {

  init_data_for_firmenistorie (state, uploadDbFirmenistorieData) {

    state.dbFirmenstorie.dbFirmenistorieData = uploadDbFirmenistorieData;
    state.dbFirmenstorie.dbFirmenistorieData.data.content_json = JSON.parse(state.dbFirmenstorie.dbFirmenistorieData.data.content_json);
    state.dbFirmenstorie.dbFirmenistorieData.data.meta = JSON.parse(state.dbFirmenstorie.dbFirmenistorieData.data.meta);

      for (let i = 0; i < state.dbFirmenstorie.dbFirmenistorieData.data.company_history_data.length; i++) {

        if(state.dbFirmenstorie.dbFirmenistorieSortArrayData.indexOf( Number( state.dbFirmenstorie.dbFirmenistorieData.data.company_history_data[i].company_history_from_year )) == -1 ){
          state.dbFirmenstorie.dbFirmenistorieSortArrayData.push(Number(state.dbFirmenstorie.dbFirmenistorieData.data.company_history_data[i].company_history_from_year));
        }

        if(state.dbFirmenstorie.dbFirmenistorieMaxYearData < Number(state.dbFirmenstorie.dbFirmenistorieData.data.company_history_data[i].company_history_from_year)){
          state.dbFirmensto....

Answer №1

By incorporating the catch() method with axios, you can effectively manage any non-200 responses that may arise. This includes handling 404 errors, 40x errors, 50x errors, and more.

axios
.get("https://example.com")
.then(res => console.log(res))
.catch(e => console.log(e))

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

Encountering an 'undefined' property error when clicking a button in Angular 1.x

Hey there, I have a question that might seem simple to some of you. I'm struggling with fixing an error and I don't quite understand why it's happening :( This error popped up while using Angular 1.x. What I need help with is creating an al ...

Streamline the process of sorting through 2 arrays

Is there a more concise and elegant way to achieve the same functionality as my current method? I am looking for a shorter solution to create an array of items that haven't been used in the form previously, which are then used to populate a select dro ...

Using React: Implementing conditional checks within the render() method of functional Components

When working with my usual React class Components, I typically perform some checks within the render() method before returning conditional html rendering. However, when using a react functional component, I noticed that there is no render() method availabl ...

Exploring the intricacies of parsing nested JSON data

Could someone assist me with understanding the following json data? { "Message":"The request is invalid.", "ModelState":{ "model.ConfirmPassword":["The password and confirmation password do not match.","The password and confirmation passwo ...

When a specific function is called, the DayPickerRangeController in the airbnb/react-dates library will update the

Is it possible to dynamically set the visible month in DayPickerRangeController after the component has been rendered? I have a 'handleMonthChange' function that I want to use to change the visible month, but setting 'initialVisible' mo ...

Using anchor tags to send HTML code through email

I currently have an anchor tag on my website that looks like this: <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e0d11131b11101b3e0d11131b09161b0c1b501d1113">[email protected]</a>?subject=Wel ...

Utilize React and Jest to handle errors by either mocking window values or resolving them

When my app attempts to inject environmental variables at runtime for docker using the window object, I encounter errors in my tests. The code snippet below shows the configuration: url config: declare const window: Window & typeof globalThis & ...

JavaScript is failing to pass the argument value

Whenever I attempt to pass a value on an onclick=function('') function, the value does not seem to get passed correctly while ($row = mysqli_fetch_array($result)) { $id = $row['id']; echo '<a href="#" onclick="DeleteUse ...

Is it possible to retrieve the createdAt timestamp without displaying the 'GMT+0000 (Coordinated Universal Time)'?

After conducting an extensive search, I have yet to find a satisfactory answer. My goal is to configure it without including the CUT time. {name: "Registered:", value: `${user.createdAt}`}, {name: "Joined:", value: `${message.guild.joinedAt}`} Presently, ...

Guide on creating an autonomous select-all checkbox to show table columns

How can I create checkboxes with a "Select all" option and the following functionality: Check one or more checkboxes to show specific table columns. Uncheck them to hide the columns (toggle). Select the "Select all" checkbox to display all table columns. ...

"Error: The function $(...).autocomplete is not recognized" in conjunction with Oracle Apex

Currently experiencing some frustration trying to solve the issue at hand. The Uncaught TypeError: $(...).autocomplete is not a function error keeps popping up and I have exhausted all resources on Stack Overflow in an attempt to fix it. This problem is oc ...

Javascript - Unable to update button text

I am encountering a problem with updating the text of a Bootstrap button when a collapsed element is opened or closed. The icon part is updating successfully, but I am struggling to get the button text to update and I cannot figure out why. My knowledge o ...

Using TypeScript with Vue and Pinia to access the store

Is it necessary to type the Store when importing it to TypeScript in a Pinia Vue project? // Component <p>{{ storeForm.firstName }}</p> // receiving an error "Property 'storeForm' does not exist on type" // Store ...

A distinctive noise is heard when hovering over multiple instances of a div

I'm trying to implement a feature where a unique sound plays when hovering over a specific div element with a particular class (.trigger). However, I am encountering an issue where multiple instances of this div class result in the same sound being pl ...

Differences between the application/xml and text/xml MIME types

How can I receive an XML response from a servlet? The servlet returns a content type of "application/xml". When using XmlHttpRequest, I am able to get responseText, but not responseXml. Could this be related to the content type or the request type (I' ...

Resize a span's width using the width of another element using only CSS

Website Development <div class="container"> <div id="setter"> <span>some unique content here</span> </div> <div class="wrap"> <span> different text goes here, different text goes here, diffe ...

Angular allows for the creation of dynamic and interactive scenes using Canvas and Three.js

I am in the process of developing a collection of web apps within an Angular SPA. Each individual application is encapsulated within an Angular template, and when navigating between them, specific DOM elements are replaced and scripts from controllers are ...

Having difficulty linking a click event to an Anchor tag within a React component

Here is the code snippet for ComponentA.js: This is the return statement inside the component return ( ...... <a id="MytoolTip" ...... <ComponentB content={ ` <div class="share_cart_tt ...

What methods can I utilize to increase the speed of my JavaScript animation?

Recently, I implemented a Vue component designed to loop a div over the X axis. While it functions correctly, I can't help but notice that it is consuming an excessive amount of CPU. I am interested in optimizing this animation for better performance. ...

Internet Explorer 11 Freezes Unexpectedly with Dynamic SVG Components

Lately, I developed a unique SVG Icon control for the new html application at my workplace. However, our quality department started noticing that IE 11 would intermittently "crash" while using the application after its implementation. I'm not convinc ...