Home > Net >  How can I fix the scope of a array variable so that I can map through it in React?
How can I fix the scope of a array variable so that I can map through it in React?

Time:08-17

I have the following code:

const getNFTs = async (address: string) => {
... // hidden for brevity

    //Nested code
    const promises = Array.from({length: output.toNumber()}).map() => {
        ... // hidden for brevity
    }

const promiseArray = await Promise.all(promises); //returns object
const imageArray = Object.values(promiseArray); //converts to array
}

If I was to console.log imageArray I am given an array like this:

['https://imagepath.com/image1.png','https://imagepath.com/image2.png','https://imagepath.com/image3.png',]

I want to use imageArray to map through the array and render a grid of images on the UI. But when I try to map through this, I get an error that imageArray is not defined most likely due to scoping issues.

Do I write the map function (with the required HTML/JSX markup) within the getNFTs async function? Or is there a better way to access the array to generate the list of images on the UI?

CodePudding user response:

promiseArray should already be an array of image URLs, Object.values will effectively yield the same value. Recall that an Array is just a special object of associative key-value pairs, i.e. the keys are the array indices and the values are the stored array values. If the returned resolved value isn't the image URLs then you can likely "unpack" them higher up in the Promise chain when processing the asynchronous requests.

You can save this array to the outer scope by adding some React state to hold this array value, and enqueue a state update to save it and trigger a rerender.

Example:

const [imageArray, setImageArray] = React.useState([]);

...

const getNFTs = async (address: string) => {
  ... // hidden for brevity

  //Nested code
  const promises = Array.from({ length: output.toNumber() }).map() => {
    ... // hidden for brevity
  }

  const imageArray = await Promise.all(promises);
  setImageArray(imageArray);
};

...

Later you can reference the imageArray state and render it as necessary.

imageArray.map(.....)
  • Related