Home > Back-end >  Pushing/Apending API response to an array
Pushing/Apending API response to an array

Time:11-19

I am trying to create an array of urls, the array is called "sentences". So far I have seen that you must use a useState if you want to put the API response in an array. This is what I have tried so far.

  const [sentences, setSentences] = useState([]);

  const getOpenAIResponse = () => {
    for (var i = 0; i < 6; i  ) {
      openai.createImage({
        prompt: prompts[i],
        n: 1,
        size: "256x256",
      }).then((response) => {
        setSentences(response.data.data[0].url)
        console.log(sentences)
      })
    }
  };

The issue is sentences just refreshes with the next url response that is generated. Using setSentences.push(...) does not work. Is there anything you would you recommend?

CodePudding user response:

New notes

It looks like I didn't take into account that, when getOpenAIResponse runs, you call openai.createImage 6 times, and each time that runs you get a URL that needs to be added to sentences. Here's some updated code that should work for you:

const getOpenAIResponse = () => {
  imagePromises = [];

  // Collect all image promises in an array
  for (var i = 0; i < 6; i  ) {
    imagePromises.push(
      openai.createImage({
        prompt: prompts[i],
        n: 1,
        size: "256x256",
      })
    );
  }

  // Do something once all promises resolve
  Promise.all(imagePromises)
    .then((responses) => {
      setSentences([
        // Keep current list of sentences
        ...sentences,

        // Add new sentences to old list of sentences
        ...responses.map(response => response.data.data[0].url),
      ]);
    });
};

Old notes

Where you have setSentences(response.data.data[0].url), this is only going to replace your existing ARRAY of sentences with one specific sentence returned by openai.createImage. What you want, is you want to take the returned URL, add it to your sentences array, then update the state.

To do this, replace your setSentences line with setSentences(sentences.concat(response.data.data[0].url))

I don't see how you were using .push before, but .push doesn't "return" the updated array, .concat does!

You can see this at work in the Chrome developer console with these two tests:

// This returns 4 which is the size of the array!
[1,2,3].push(4);

// These return [1,2,3,4] which is the new array, with the added new element at the end
[1,2,3].concat(4);
[1,2,3].concat([4]);

CodePudding user response:

You can use the spread operator to add the new url to the array.

setSentences([...sentences, response.data.data[0].url])

You can also use the concat method to add the new url to the array.

setSentences(sentences.concat(response.data.data[0].url))
  • Related