1

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?

2 Answers 2

3

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]);
Sign up to request clarification or add additional context in comments.

13 Comments

Shouldn't the argument be wrapped in an array?
@CherryDT not needed, if you're only appending 1 element to the sentences array, you don't need to wrap response.data.data[0].url in an array
It will behave unexpectedly if that element itself is an array though, so it's best to learn it consistently from the start to avoid future surprises. Alternatively I'd recommend the (arguably cleaner) [...sentences, response.data.data[0].url] syntax.
That's exactly what's unexpected about it. If you learn "a.concat(x) will append x to the array", you will be surprised about the case you just showed, where x would have been [3] and not 3, yet what was added to the array was 3. I'm a fan of clearly-defined universal tools to learn where you won't have to keep in mind edge cases later on (an example of a similar issue would be new Array(...) where passing a single argument which happens to be a number will lead to entirely different behavior than all other cases - and that's even the reason why it was deprecated). My two cents.
Thank you. For some reason the same problem is persisting. Sentence[0] changes 6 times, and once I click the button that activates the API response again I get Sentence[1] which also regenerates 6 times. It doesn't seem to give me an array of urls as I want.
|
2

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))

1 Comment

Thank you, but for some reason the same problem is persisting. sentences[0] changes 6 times, and once I click the button that activates the API response again I get sentences[1] which also regenerates 6 times. It doesn't seem to give me an array of urls as I want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.