Attempted to access a variable prior to giving it a value (TypeScript)

I am struggling to extract the ImgString from an array retrieved from an API and assign it to the base64 property of a photo object, but I keep encountering an error. As someone new to react, typescript, and javascript, I'm unsure where my code is going wrong.

import { useState, useEffect } from "react";

export function getImages() {
  const [photos, setPhotos] = useState<Photo[]>([]);

  const GetPhotoURL = "***"

  useEffect(() => {
    const loadSaved = async () => {
      const data = await axios.get(GetPhotoURL)
        .then(res => {
          const photos = [] as Photo[];

          for (let i = 0; i <= res.data.length; i++) {
            var photo: Photo = {};

            photo.base64 = `data:image/jpeg;base64,${res.data[i].ImgString}`;

            photos.push(photo);
          }

          setPhotos(photos);
        })
    };
    
    loadSaved();
  }, []);

  return {
    photos,
  };
}

export interface Photo {
  base64?: string;
}

Answer №1

The variable photo is declared but not assigned when you write (thus resulting in the error - "used" before "assigned"):

var photo: Photo; // line 1
photo.base64 = `data:image/jpeg;base64,${res.data[i].ImgString}`; // line 2
// at line 2, you are attempting to access the base64 property of photo without assigning it first

You have two options:

var photo: Photo = {}; 
photo.base64 = `data:image/jpeg;base64,${res.data[i].ImgString}`;
photos.push(photo);

or

var photo: Photo = {
  base64: `data:image/jpeg;base64,${res.data[i].ImgString}`,
}
photos.push(photo)

For more information on the difference between declaration and definition, you can visit this link.

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

What is the process for incorporating various cameras with orbit controls?

My Situation: In this scenario, I have setup two cameras - one displayed in the 3D space and the other recording that specific area. The code snippet below is used to create and configure these cameras along with the orbit controls. https://i.sstatic.net ...

Troubleshooting Proxy.php issues in conjunction with AJAX Solr

Attempting to access a Solr 4.5.0 instance located on a private server, http://12.34.56.789:8983/ The application resides at this web server address, http://www.mywebapp.com To facilitate accessing the JSON object within the Solr instance, I decided to ...

Importing CSS files from node_modules in JavaScript modules can lead to CSS class names becoming "undefined" in the generated HTML

After successfully importing CSS/SCSS files into my React modules using Parcel, I encountered an issue when trying to import a CSS file from a node_modules package like bootstrap: import * as styles from 'bootstrap/dist/css/bootstrap.css'; .... ...

How come my web page is not displaying the guages from guage.js?

I am utilizing guage.js to create a graph based on this Fiddle. However, upon adding the same code to my website, the rendering does not appear as expected: https://i.sstatic.net/fIkQr.png Upon inspecting in Chrome developer tools, I noticed that the ele ...

Include a predetermined parameter for the upcoming callback

Currently, I am working on loading files asynchronously by utilizing d3's queue, defer, and await features. The issue arises when I attempt to execute this process in a loop, where for each iteration, I aim to store the retrieved data in a dictionary: ...

Toggle the visibility of a text area in a text editor based on the selected value in a

I currently utilize the NicEdit text-editor from www.nicedit.com on my Text Area, along with the following code to toggle the visibility of the text area after selecting a value from a drop-down. I need some assistance with the following: 1) I would like ...

Conceal and reveal div elements using hyperlinks

Hey everyone, I've been working on some code that allows me to show and hide divs by clicking on links. The issue I'm facing is that when I try to view a specific div (like the third one), it appears below the invisible divs instead of at the top ...

Is it possible to update the state before initiating an API call that relies on that specific state in React?

useEffect(() => { resetState(); if (page === 'ADMISSION') { fetchAdmissionKitPosts(); } else if (page === 'WEEKLY') { fetchWeeklyKitPosts(); } else if (page === 'FESTIVAL') { fetchFestivalK ...

What is the most effective method to retrieve the current browser URL in Angular 2 with TypeScript?

Is there a way for me to retrieve the current URL from the browser within my Angular 2 application? Usually in JavaScript, we would use the window object for this task. Can anyone guide me on how to achieve this in Angular 2 using TypeScript? Appreciate a ...

Manipulating Objects Using Controls with a Simple Drag and Click

Currently, I'm working on a scene that consists of two spheres and a point light positioned at (0,0,0). Using Controls, I've managed to make the spheres rotate around the point. However, I'm having trouble getting the spheres to move when I ...

Is it possible to authenticate across multiple tables in a React/Node.js environment?

I am currently planning an online library management system project. For this project, I have identified **3 distinct roles** which are stored in separate database tables. Firstly, there is the user role, which will have an interface allowing them to view ...

Is it possible to change the hover highlight rotation on a link without affecting the surrounding elements?

Is it possible to rotate the highlight on a link when hovered? I'm new at this, so apologies if this question seems basic. This is how my css/html is currently structured: .links { display: block; } .links a { color: #000000; text-decoratio ...

Express js is failing to deliver static assets

Hello, I'm having an issue with Express Js. It seems like a beginner problem - static files are not being served properly. const express = require('express'); express() .set('view engine','ejs') .use(express.stat ...

Increase or decrease the selected item in a React dropdown by clicking on the arrow buttons

I am working on a dropdown input that allows the user to move the currently selected option forward or backward by clicking left or right arrow buttons next to the input. Additionally, I want the dropdown to update when an option is selected directly from ...

Issue with disabled dates not refreshing in the view after adding them via button click

I have been utilizing the vue-hotel-date-picker plugin and it's been functioning well. The problem arises when I use the disabled dates props; it disables the dates initially when initializing and updating on the calendar. However, when I update the d ...

Return Date objects in Node.js, not strings

When working with nodejs and express, I've encountered an issue where Date objects are automatically converted to strings. This has caused some confusion for me as I would prefer to send Date objects directly as a result. app.get('/', (req, ...

The result of jQuery is an Object Object in a dynamic and user-friendly web application

Working on an application that requires the use of JQuery has brought up an issue with my functions related to sons and grandsons in the code below: When typing http://localhost:8080/fathers into my browser, I receive the following response: [{"id":1," ...

Despite using preventDefault and returning false, the user is still being redirected after submitting the form

I'm in the process of trying to send a form using JQuery's .ajax function without having the user redirected upon submission. The form and backend code are both functioning as expected. However, I am encountering an issue when it comes to prevent ...

What is the best way to retrieve the content of a p tag in React?

How can I access the content of a p tag within an obj and render it through props without using the dangerouslySetInnerHTML method? let content = { para: `<p>A listing page is the public view of a listing. It should informations be designed to ...

What could be the reason my hex code generator is outputting variable names instead of their assigned values?

I am currently working on developing a unique hex code generator using random values. At the moment, my focus is on displaying six random values in the HTML. // The characters A-F and numbers 0-9 can be utilized var button = document.querySelector(&quo ...