Learn how to dynamically assign an image property as the src attribute on an asynchronous object in Vue

I am still new to Vue and navigating my way through the learning process. I have been able to successfully fetch data from an endpoint, which is returned as an object. The object is making it into the component as verified by both the devtools and on the page. However, despite having all the necessary data, I am struggling to access the url property that exists within the info object. My attempts so far have not yielded any positive results.

Here is the error message I am encountering:

TypeError: Cannot read property 'url' of null

I am wondering if there might be a different approach or lifecycle method that I should be utilizing for handling async behaviors?

<template>
  <div class="SpaceImage">
    <img :src="info.url" />
    <p>{{info}}</p>
  </div>
</template>

<script>
import axios from "axios";
import { API_KEY } from "../../API_KEY/API_KEY";

export default {
  name: "SpaceImage",
  data() {
    return {
      info: {},
      imnageData: ''
    };
  },
  created() {
    axios
      .get(`https://api.nasa.gov/planetary/apod?api_key=${API_KEY}`)
      .then(response => (this.info = response))
      .catch(error => console.log(error));
  }
};
</script>

<style>
.SpaceImage {
  border: 1px solid red;
  height: 100px;
  width: 100px;
}
img {
  width: 100px;
  height: 100px;
  border: 1px solid blue;
}
</style>

Answer №1

Hey Kevin, I wanted to address a couple of things in relation to the issue you're facing. First, @helikat_ made a suggestion, and secondly, there's this code snippet:

.then(response => (this.info = response.data))

The key here is to extract the data property from the response object as it holds the actual content of the response.

Answer №2

Make sure to store the current value in a variable before making your axios request.

created() {
const currentValue = this;
axios
  .get(`https://api.example.com/data?key=${API_KEY}`)
  .then(response => (currentValue.info = response.data))
  .catch(error => console.log(error));
}

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

Cursor-hugging tooltip

My tooltip creation works when hovering over an icon, but there's a slight issue - it doesn't always follow the cursor and can get stuck at times. To see a demo of this in action, click here: fiddle Here's the code I'm using: HTML & ...

Submit a collection of images and an object to the server using ReactJS

I'm currently working with Reactjs on the frontend. In order to set the profile picture to state, I've implemented the following code: handleImageChange = (event) => { event.preventDefault(); var file = event.target.files[ ...

Node.js and Express - Dealing with Callbacks that Return Undefined Prematurely

I've hit a roadblock with this issue that's been haunting me for weeks. The first function in my code queries a MySQL database and returns a response, which is then processed by the second function. The problem lies in the fact that JavaScript ...

implementing a new CSS file to replace the existing one

Is there a way to dynamically load CSS properties in JavaScript? I have two canvases and I've already linked a CSS file in the head tag. I'm looking for a solution where when a specific option is selected, the CSS properties of the canvases cha ...

What exactly does the 'value' attribute do when used in an input element within React?

Can someone explain the significance of value={} in React inputs? Currently, I am working with a state defined as const [username, setUsername] = useState("");. In my form, there is an input element that updates the state based on user input. &l ...

The issue with the datatable row button functionality is not functioning as expected within the

I am facing an issue with my Jade Template code where I am trying to trigger a JavaScript function when a button is clicked on each row. Despite following the documentation for DataTables and Jade, I am unable to figure out what mistake I am making. It see ...

Tips for optimizing Firestore database requests on the web to minimize the number of API calls

On my product page, every time a user presses F5, the entire list of products gets loaded again. I am looking for a way to save this data locally so that it only needs to be updated once when a new product is added, instead of making multiple API calls. ...

Incorporate URL parameters with props object in Vue router configuration

Sharing my current router setup. const router = new VueRouter({ routes: [ { path: '/user/:id', components: User, props: { sidebar: true } } ] }) However, I am only able to access the sidebar prop in t ...

Collaborative gaming experience with three.js and socket.io

I created a basic scene in three.js that I find really fun to interact with. However, I wanted to enhance it by adding multiplayer functionality through a socket.io server. To achieve this, I prompt the user for their username: var username = prompt("what ...

Transferring data from AJAX form in JavaScript to PHP function

My website features a login form that sends data, such as email address, to a PHP function and initiates the creation of a user. I am looking to include additional information on the page where the form is located. Here is the data I want to include in t ...

Creating an array by extracting items from a textarea that are separated by line breaks

I am working with a textarea that has the id #list : $text = $('#list').val(); The goal is to split this text into pieces and place each piece as a new item in an array. This array will then be sent to PHP, where I can utilize it in a foreach l ...

What is the best way to add information stored in localStorage to an element on the webpage?

At the moment, I am developing a Bookmark manager that stores data in localstorage and then adds the saved data from localstorage to the DOM. However, I am facing an issue where the code inside fetchUrl() is not getting appended to the DOM. Here is what I ...

What is the best way to use useCallback within loops?

I am currently exploring the concepts of memo and useCallback, and to better grasp them, I have created a simple example: import { memo, useCallback, useState } from "react"; import { Button, Text, TouchableOpacity, SafeAreaView } from "reac ...

What is the most effective method for implementing a debounce effect on a field in React or React Native?

Currently, I am working on implementing a debounce effect in my useEffect. The issue is that the function inside it gets called as soon as there is a change in the input value. useEffect(() => { if (inputValue.length > 0) { fn(); ...

Choose up to three elements using jQuery

DEMO I'm currently working on a project where I need to select only 3 items at a time. However, all the elements are being selected instead. Can someone please provide guidance on how to achieve this? "If a user wants to select another element, th ...

Ensuring Proper Tabulator Width Adjustment Across All Browser Zoom Levels

<div id="wormGearTabulatorTable" style="max-height: 100%; max-width: 100%; position: relative;" class="tabulator" role="grid" tabulator-layout="fitDataTable"><div class="tabulator-header" role="rowgroup"><div class="tabulator-header-co ...

What is the syntax for using escape characters in Vue?

Looking to create a website similar to CodePen? I have developed a library of assets including buttons, cards, and effects, all built using vue.js. Each asset includes HTML, CSS, and sometimes JS code. In my vanilla JS version, I formatted the code using e ...

Emulate clicking a radio button (using PHP and JS)

For the past week, I've been struggling to solve this issue with no luck. I admit that I am new to this area, so I ask for your patience. My current problem involves using TastyIgniter, an online food ordering system. In order to add items to the car ...

Having trouble with a dropdown menu that allows for multi-select options?

var expanded = false; function showCheckboxes() { var checkboxes = document.getElementById("checkboxes"); if (!expanded) { checkboxes.style.display = "block"; expanded = true; } else { checkboxes.style.display = "none"; expanded = fa ...

Using Javascript, ensure that the drop-down menu remains on the currently selected item

Can someone assist me with my issue regarding the drop-down menu not staying on the selected value after submitting? I believe the problem lies within the javascript code. I appreciate any help as I am trying to learn this on my own. function GetSelect ...