I have the following state and function
const [obj, setObj] = useState([])
const getData = async (e) => {
e.preventDefault();
const text = e.target.input.value;
const payload = {
input: text,
};
const response = await fetch(process.env.API_LINK, {
body: JSON.stringify(payload),
headers: {
Authorization: `Bearer ${process.env.API_KEY}`,
"Content-Type": "application/json",
},
method: "POST",
});
if (response.ok) {
const data = await response.json();
const output = data.choices[0].text;
setObj(obj => [...obj, {input: text, output: output}])
}
};
return (
<form onSubmit={(e) => getData(e)}>
<input name="input"/>
</form>
)
The issue is that when the state obj is empty it doesn't get updated when the function first runs, it has to be run twice for obj to be updated. The response from the API and everything else is fine.