0

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)

enter image description here

enter image description here

James Z
  • 12,209
  • 10
  • 24
  • 44
  • It is because `setState` is async so when you do the second `setMessages`, `messages` isn't already updated. – OneQ May 25 '23 at 22:20
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Konrad May 25 '23 at 22:59

1 Answers1

0

You are missing some key point relative to react and components update. Everything (or at least a lot of things) is asynchronous, like @OneQ said, so you should use the UseEffect hook and change your logic.

Regarding userIndput and outputValue you want to do something, so you can use this implementation :

useEffect(() => {
    //will run at the component loading because array is empty, see second argument of useEffect
},[])

useEffect(() => {
    //will trigger every time userInput or outputValue change
    if (userInput && !outputValue) {
         //if my conditions are what I want do something
    }
}, [userInput, outputValue]);
Porzio Jonathan
  • 536
  • 2
  • 13
  • sorry for the delayed reply but useEffect did work in the end, i did try using useEffect hook before but wasn't working now its working good. – Areej Khan Jul 19 '23 at 08:52