I would like to click a button to call an API. I then want to use the API response to call the API again, and use the response in the "prompt" feature the API has. The issue is, the "names" state in the second API response is the name I got on the last button click, and not the current one.
For example, I click the button once, and the API sets names = "Jeff", then the second time I click it sets names = "John", the sentence on the second click will still be about Jeff and not John.
const [names, setNames] = useState([]);
const [sentence, setSentence] = useState([]);
const getOpenAIResponse = () => {
openai.createCompletion({
model: "text-davinci-003",
prompt: "Create a unique name.",
max_tokens: 256
}).then((response) => {
setName(response.data.choices[0].text)
openai.createCompletion({
model: "text-davinci-003",
prompt: "Create a sentence long story about a character called" + names + ".",
max_tokens: 256
}).then((response) => {
setSentence(response.data.choices[0].text)
})
})
...
<Button onClick={getOpenAIResponse}></Button>
Originally, I put the second openai.createCompletion outside of then((response)), but that did not work. I was told that putting it inline would fix it. However, I still have the same problem. Is there a solution?