Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable is used before being assigned (TypeScript)

I am trying to get the ImgString inside of an array that I get back from an API and assign that string it to the base64 property of the photo object but it display this the error. I am new to react and tyescript/javascript so I am not sure where did it go 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; 
}
like image 716
Jared Luu Avatar asked May 07 '20 22:05

Jared Luu


1 Answers

Your photo variable is declared but not assigned when you write (Hence 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 trying to access the base64 property of photo which is not yet assigned

You should either write this:

var photo: Photo = {}; // declaration + assignment
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}`,
} // declaration + assignment
photos.push(photo)

You can read the difference between declaration and definition.

like image 186
Ajeet Shah Avatar answered Sep 22 '22 06:09

Ajeet Shah