I am a freelancer who recently started development working with nextjs and reactjs. I am having issues in understanding why the useState hook array won't update data correctly.
I am using one useState hook to store arrays in two different positions in same function, once before the api call and next after the api call.
Till the api is called the state before the call is stored correctly but after the api call new state is stored as well but it replaces the previously stored state and no matter how many times i run the array would only store all the data after the api call and the one stored before would be replaced.
For context i am trying to make a chat-box.
const [userInput, set_userInput]= useState(false)
const [outputValue, set_outputValue]= useState(false)
const [answer, set_answer]= useState([])
const [history, set_history]= useState([])
const [newMessage, setNewMessage] = useState('');
const [messages, setMessages] = useState([])
console.log("outside of function",messages)
async function UserInputAllow(){
set_userInput(true)
set_outputValue(false)
const input = document.getElementById("input").value;
// console.log("before user save",messages.length)
const usernewId = messages.length + 1;
setMessages([...messages, { id: usernewId, role: "user", text: input }]);
try {
const data = {
key:input
}
console.log("before call",data)
const resp = await Chat_Usecase(data)
if (resp.status === 200 || resp.status === 201){
console.log("system chat reply",resp)
console.log("user save",messages.length)
const newId = messages.length + 1;
setMessages([...messages, { id: newId, role: "assist", text: resp.data }]);
}
console.log("convo history",messages)
} catch (error) {
}
}
console.log("below func",messages)