Storing the output of a GET request in a text file can lead to a never-ending loop

After attempting to save a String obtained from a GET request into a text file, I encountered an unexpected infinite loop issue. It seems that without utilizing created(), the process fails entirely, resulting in story remaining empty.

<div id="app">
    <p>{{story}}</p>
    <a id="link" v-bind:href="url" target="_blank" download="file.txt">Download</a>
</div>

<script>
    var str = {
        data: function () {
        return {
          story: '',
          file: null,
        }
    },
    methods: {
        async getStory(id) {
          var req = 'http://localhost:8080/api/story/' + id
          try {
            const response = await axios.get(req);
            return response.data.story;
          } catch (error) {
            console.error(error)
          }
          return false;
        },
        async getLetter() {
          var letter = await this.getStory(this.$route.params.id);
          this.story = letter;
        },
        textFile() {
          var data = [];
          console.log(this.story);
          data.push(this.story);
          var properties = {
            type: 'text/plain'
          };
          try {
            this.file = new File(data, "file.txt", properties);
          } catch (e) {
            this.file = new Blob(data, properties);
          }
          this.url = URL.createObjectURL(this.file);
        }
      },
      created() {
        this.getLetter();
      },
      updated() {
        this.textFile();
      }
    }
</script>

Is it advisable to leverage the HTML5 function for saving files?

Answer №1

Axios is a promise-based HTTP API, therefore removing the async/await keywords will suffice

fetchStory(id) {
      return new Promise((resolve, reject) => {
          var request = 'http://localhost:8080/api/story/' + id
          axios.get(request).then((response) => {
              resolve(response.data.story);
           }).catch((error) => {
              reject(error);
           });
      })
    },
    fetchLetter() {
      var story = this.fetchStory(this.$route.params.id);
      this.story = letter;
    }

Additionally, there is no infinite loop occurring, but rather the request is not yet complete.

Answer №2

If you're looking for some code to try out, take a look at the snippet below:

var app = new Vue({
  el: '#app',
 data () {
    return {
      story:"",
      url:"",
     
    }
  },
  created(){
this.getLetter();
  },
  methods: {

        getStory:function(id) {
             var req = 'http://localhost/website-one-pages/slipt.php?id=' + id;
 axios.get(req).then((response) => {
              this.story = response.data;
              
              //set download
              var data = [];
              data.push(this.story);
              var properties = {
            type: 'text/plain'
          };
          try {
            this.file = new File(data, "file.txt", properties);
          } catch (e) {
            this.file = new Blob(data, properties);
          }
          this.url = URL.createObjectURL(this.file);
          //end set download

           }).catch((error)=>{
                console.log(error);
              });
        },
        getLetter() {
          var id =2;//example id=2 
          this.getStory(id);
        },
    }
    
})
<div id="app">
    <p>{{story}}</p>
   
    <a id="link" v-bind:href="url" target="_blank" download="file.txt">Download</a>

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

Using Angular's Jasmine SpyOn function to handle errors in $resource calls

I need to write unit tests for an AngularJS service that utilizes $resource. I want to keep it isolated by using Jasmine's spyOn to spy on the query() method of $resource. In my controller, I prefer to use the shorter form of query() where you pass su ...

VS Code failing to refresh TypeScript in Vue files

Currently, I'm using Vue with Vue Single File Components (SFC) and TypeScript in vscode. However, I've noticed that the types I create in a .d.ts file are not being applied or updated in my .vue files. It's only when I reload the window that ...

Challenges encountered when using setState to assign values

Just started using React and running into an issue with updating state when changes are made to a Textfield. I'm working with a functional component where the initial state is set using useState. I feel like I might be overlooking something simple... ...

The Javascript code I wrote is unable to detect the array element that was initially defined in Python

Trying to launch a new browser window through Selenium using driver.execute_script("window.open('');") However, the goal is to open a specific link provided by the user. For this purpose, extracted the link input from an array and inc ...

Guide to displaying a canvas as an image in a new tab using Reactjs

My current project involves using a canvas barcode generated by the react-barcode library. At the moment, I can only right-click on the canvas to open it as an image in a new tab. Is there a way to achieve this functionality with just a click of a button i ...

Utilizing the Filter Function to Eliminate an Element from an Array

I am a beginner in the world of React and I'm currently working on developing a simple timesheet tool where users can add tasks and save them. My tech stack includes React and Typescript. Currently, my main component has an empty array for tasks and ...

Latest versions of Bootstrap are facing issues with the functionality of the Carousel feature

I'm struggling to create a basic carousel, but for some reason, it's not functioning properly. I attempted to use the sample code provided by Bootstrap's documentation, but it doesn't behave as expected (slides won't transition and ...

Error message indicating that a TypeError is occurring specifically while using the

For the past two days, I've been encountering an error when attempting to upload files using AJAX with angularJS. The error occurs after selecting the file to upload, and it's a TypeError: TypeError: Failed to execute 'append' on &apos ...

Utilizing a JavaScript variable within a jQuery function as an attribute

var image = "path.png"; Is it possible to include the 'image' variable in the jQuery function like this? $('#mapfoto').prepend('<img id="theImg" src="http://path.gr/" + image />'); ...

Toggle switch with active state

I'm currently using Ionic 2 alongside Angular 2 beta 11. Is there a way to turn off the toggle switch? The Ionic documentation suggests using the checked attribute, but I've tried that and also attempted ng-checked with no luck. Any advice on t ...

What could be the reason behind Typescript's unexpected behavior when handling the severity prop in Material UI Alerts?

Trying to integrate Typescript into my react project and encountering a particular error: Type 'string' is not assignable to type 'Color | undefined'. The issue arises when I have the following setup... const foo = {stuff:"succes ...

Using React hooks to update the state of an array from one component to another

I am currently working on a MERN blog website project and I've encountered an issue while trying to update comments on a post. I'm editing the comment from another component but facing difficulty in updating the state after making changes. Would ...

Unable to retrieve module from directive template in Angular

I am currently working on creating a wrapper component for ngAudio. This wrapper will act as the player with controls and will interact with ngAudio's functions. However, I am facing some scope issues with it. I can inject ngAudio into the component&a ...

What is the best way to retrieve the current font size of a link element?

Is there a way to determine the font size of an element in pixels or points? Are there alternative methods available to achieve this? I am looking to increase the size of <a href="...">MAKE ME BIGGER</a> by 130%, 140%, N% based on its current ...

Implementing a timed delay before assigning a class in the state

I am trying to implement a delay before applying for a new class. This is my current situation const [isDone, setIsDone] = useState<boolean>(false); Within a method, I have the following code snippet const myMethod = () => { .... .... se ...

Trouble Connecting Local Database with PG NPM Package

I'm encountering issues with using the pg package on my computer. I've attempted to execute the following code: var pg = require('pg'); var con_string = "postgres://user:password@localhost:5432/documentation"; var client = new pg.Clie ...

Tips for managing input for objects in Vue when the object hasn't been declared yet?

<input type="text" v-model="object[obj]"> Output: object:{'obj1':value} Desired outcome after input is added: object:{'obj1':{'prop1':value,'prop2':value}} <input type="text" ...

Submitting form data via Ajax without refreshing the page

I am trying to submit my form using Ajax without refreshing the page. However, it seems that the $_POST values are not being picked up. I don't receive any errors, but I suspect that my form is not submitting correctly. HTML Form <form action="" ...

Tabindex issue arises due to a conflict between Alertify and Bootstrap 4 modal

When trying to call an Alertify Confirmation dialog within a running Bootstrap 4 Modal, I encountered an issue with the tab focus. It seems to be stuck in the last element and not working as expected. I suspect that this might have something to do with th ...

Having difficulty retrieving the necessary information for manipulating the DOM using Express, Ajax, and Axios

When working on DOM manipulation based on AJAX calls, I've encountered an issue where the response is being displayed on my page instead of in the console.log output. This makes it difficult for me to view the data and determine what needs to be inser ...