0
votes

How do I get access to data stored as a Promise[] in ES6 array? I am loading an array from the backend and each object has a url for the image. So in order to render the image I have to async/await fetch the images for each object. Instead of returning a Base64 image, I get I promise with the image embeded deep in the promise. I need a way to read the image data. See image below for return object structure.

Please note that i use axios in the background and NOT the Fetch API

Image field contains a promise instead of Base64 data

Below are the functions and service methods used to load the list and then the images in 2 steps.

1.1 Axios service method

listAllItems() {

    return axios.get(API_URL + "docman/items/list/all");
}

1.2 ReactJS main function

    async componentDidMount() {

    try {

        const items = await DocmanService.listAllItems();
        const itemsData = items.data;

        const data = await itemsData.map(item => {

            const image = this.loadImage(item.image);
            return { ...item, image: image }
        })

        this.setState({ items: data });

    } catch (e) {

        console.log(e);
    }
}

2.1 Axios images service method

loadImage = (url) => {

    return axios.get(API_URL + url, { responseType: 'arraybuffer' });
}

2.2 ReactJS image loader function

 async loadImage(imageUrl) {

    try {

        return await ImageService.loadImage(imageUrl)

    } catch (e) {

        return '';
    }
}

3.1 Json list fetched from backend

[
  {
    "id": "1",
    "uuid": "1c0a33af-4e78-4823-b84e-f3b5464db2af",
    "identifier": "EN ISO 8402",
    "title": "EN ISO 8402 Quality Management - Vocabulary",
    "folder": "e347fef9-0a76-4e62-b7f2-c78e9f88355b",
    "media": "FILE",
    "path": "document/id/105",
    "image": "image/id/106",
    "format": "PDF",
    "authors": "",
    "publishers": "",
    "created": "2020-09-22T14:56:31.316+00:00",
    "published": null,
    "version": "1994",
    "status": null
  },
  {
    "id": "2",
    "uuid": "16a0e658-b444-4b60-bf18-ba2786d5fb00",
    "identifier": "ISO 14001",
    "title": "ISO 14001 Environmenatl Management Systems - Requirements with Guidance for Use",
    "folder": "e347fef9-0a76-4e62-b7f2-c78e9f88355b",
    "media": "FILE",
    "path": "document/id/107",
    "image": "image/id/108",
    "format": "PDF",
    "authors": "",
    "publishers": "",
    "created": "2020-09-22T14:56:31.659+00:00",
    "published": null,
    "version": "2004",
    "status": null
  },
  -
  -
]
2

2 Answers

0
votes

try doing image.then((data) => { // console.log(data) })

0
votes

When you setState you are setting the new state with a list of objects with an image value that is a promise. Shouldn't you update the state only when at least one of the promise resolved to a real image? Couldn't you do something like this.loadImage(item.image).then((imageData=>setState(appropriate State)))?