Updating a reactive data within the axios response callback in the setup option of Vue 3

I am currently facing a challenge with Axios call in the Setup method of my component. My objective is to set a variable called "books". In Vue 2, I would execute the call within a created hook and utilize `this` to assign the variable. However, with Vue 3, `this` is not available in the setup method. So, my question is how can I access data outside the axios call? Specifically, my goal is to retrieve an array of books from the API and assign it to the "books" variable. What would be the best approach to achieve this in Vue 3? Below is a snippet of my setup method:

  setup() {
      let books = reactive<Array<Book>>([])
        HTTP.get('/books')
            .then(response => {
                // Usually, I would use 'this.books' here
                books = response.data
            })
            .catch(function (error) {
                console.log(error);
            })
            return { books }
  }

Answer №1

As per the information provided in the composition api documentation:

reactive
When used with an object, it creates a reactive proxy of the original ...
...
ref
When given an inner value, it returns a reactive and mutable ref object. This ref object contains a single property .value that corresponds to the inner value ...

Hence, the reactive function should have an internal property:

  setup() {
      let state = reactive<Array<Book>>({books:[]})
        HTTP.get('/books')
            .then(response => {
            
                state.books = response.data
            })
            .catch(function (error) {
                console.log(error);
            })
            return { books:toRef(state,'books') }
  }

Alternatively, you can utilize a ref

  setup() {
      let books = ref<Array<Book>>([])
        HTTP.get('/books')
            .then(response => {
              
                books.value = response.data
            })
            .catch(function (error) {
                console.log(error);
            })
            return { books }
  }

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

Verify if there are DOM elements located within a DIV container, execute the functions associated with those elements sequentially

I am in the process of creating a game using HTML, CSS, and JavaScript. My focus right now is on manipulating DOM elements without relying on the canvas tag. The goal is to develop a pseudo graphical programming language, similar to the environment provide ...

Using JavaScript to replace a radio button with the term "selected"

I am currently in the process of developing a quiz that is powered by jQuery and possibly JSON, with data being stored in a database. Everything is functioning correctly at this point, but I would like to enhance the user interface by hiding the radio butt ...

Understanding the values of attributes when submitting a reactive form

My form is built using Angular's reactive forms and includes an input element with custom attributes: <input type="text" [attr.data-challengeId]="value.id" [formControlName]="value.label"> When I submit the form, I only receive the value of th ...

Sleek animation designed for a personalized cursor when hovering over an object

I'm currently working on improving the transition of the cursor for a smoother experience. Right now, the size abruptly changes when hovered over the target element. Any suggestions on how I can achieve a smoother increase in size, with a better anima ...

Deciphering the JavaScript code excerpt

This information was sourced from (function ($, undefined) { // more code ... $.getJSON("https://api.github.com/orgs/twitter/members?callback=?", function (result) { var members = result.data; $(function () { $("#num- ...

Connection lost from JS client in Twilio's Programmable Chat

My React application utilizes the Twilio Programmable Chat library for chat functionality. The setup code typically appears as follows, enclosed within a try/catch block: this.accessManager = new AccessManager(twilioToken.token); const chatClientOptio ...

Leveraging JavaScript for Validating Radio Buttons

I've been following a tutorial guide on this specific website , but I'm encountering some difficulties despite following the exact steps outlined. Can someone provide guidance? Here is what I have done: <html> <script> fu ...

Using Vue.js - Passing a prop into $.each() within the mounted lifecycle hook

When my component is mounted, I am looking to iterate over an object literal. However, I am encountering difficulties in accessing the prop data within my .each() function. Upon checking with console.log, the prop data appears 'undefined' inside ...

Combining arrays to create a single object: A step-by-step guide

Here is the current output I have, which contains multiple arrays: ["{"486|575":2,"484|568":4}", "{"486|575":2,"484|568":4}", "{"481|570":1,"482|564":1}"] My goal is to combine these arrays into an object with the following output using JavaScript/jQuery ...

Executing the chosen code within Sublime Text

In my Sublime Text 3, I set up a custom "build system" as follows: { "cmd": ["node", "$file"] } Within my file foo.js, there are two lines of code: 01 console.log('foo'); 02 console.log('bar'); If I select line 1, is it po ...

"Can anyone provide guidance on how to initiate a css 3d animation by clicking a button

Currently, I am developing a folding hide/show animation that can be triggered using Javascript. If you would like to take a look at the code and see a working example, please visit this link: You can also view just the gist here: https://gist.github.com ...

Issues with Angular 2 loading properly on Internet Explorer 11

We are currently running an Asp.net MVC 5 web application integrated with Angular 2. The application functions smoothly on Chrome, Firefox, and Edge browsers, but encounters loading issues on IE 11, displaying the error illustrated in the image below: ht ...

Divergent functionality of regular expressions in Internet Explorer and Chrome when handling white spaces

Here is a function that validates input by checking for numbers and no spaces in between: checkInputValidity: function() { var isValid = true; var idNumber = this.getView().byId("iDNumber"); var regex = /^[0-9]+$/; if (idN ...

Guide on exporting data from ejs files to a pdf file using pdfkit in a node js environment

Below is the code from my result.ejs file: <div style="width: 50%; margin: auto;"> <table class="table"> <thead> <tr> <th>SUBJECT</ ...

Display an alert in a React Native app using Native Base based on certain conditions

I am currently working on an alert component that utilizes a Native Base alert component function CustomAlert() { const { alert, setAlert } = useAuthContext(); const clearAlert = () => setAlert({ status: "", message: "" }); us ...

Display the razor page in a modal dialog box

I want to display a razor page within a modal dialog: Here is the code for the razor page: <div class="container"> <div class="title modal " tabindex="-1" id="loginModal" data-keyboard="false" data-backdrop="static"> < ...

What are some effective ways to utilize a marquee?

I am looking for a way to duplicate the <a> tag within a DIV named box so that the text is displayed on a continuous line marquee without any breaks. As I am new here, please feel free to ask for more information in the comments. Thank you. $(&apo ...

Retrieve specific items from a handlebars array by using the loop index

Utilizing handlebars.js, I am iterating through the categories and then accessing an element in the series array using the current array index. This is achieved with the following helper function. var json={ "categories": [{ "id": 3, ...

Creating a Dynamic Bootstrap 4 Dropdown Menu using Jquery Hover

My Bootstrap Dropdown menu has a JQuery animation that is exactly what I want. However, when I move my cursor from the Dropdown's name (.dropdown) to an item in the dropdown, it starts acting erratically. $('.dropdown').hover(function() { ...

Nodemon causing crashes in basic HTML pages

Having trouble getting a basic index.html page to work with nodemon. index.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </hea ...