0

I have an issue that is kind of hard to explain but ill try my best. I have a chat app, that displays users you can talk to and when you click on a user it fetches the messages and sets a selected user on click using the useContext. Everything works when you click a user. (All the messages gets fetched). However, the user context isn't set on the first click but it works on the second click.

this is the function that's sets everything:

    const handleUserClick = (messsagesID:string, selectedUserInfo:selectedUserProps)=>{
        setSelectedUserMessages(selectedUserInfo);
        console.log(selectedUserInfo);
        selectMessage(messsagesID);
        showMessage();
    }

This is the context function:

  const setSelectedUserMessages=(selectedUser:selectedUserProps|undefined)=>{
        setSelectedUser(selectedUser);
    }

this is the chat list loop:

 {
   Object.entries(messages!)?.map((chat:any)=>(
   <div key={chat[1].userInfo.uid} className="" onClick{()=>handleUserClick(chat[0],chat[1].userInfo)}>
   <UserMessage name={chat[1].userInfo.displayName} photoUrl={chat[1].userInfo.photoUrl} message={chat[1].lastMessage.message} />
  </div>
   ))
 }

When I console log the data. Its correct I get the information back on the first click but when I try and set it to the context its empty. But on the second click it gets set correctly. This is very strange as everything else gets set as it should on the first click.

Hopefully I explain this correctly and it isn't confusing.

Mat
  • 405
  • 4
  • 12
  • You can look at this topic this may help you [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) – ShueiYang Jul 24 '23 at 15:29
  • Maybe remove the typescript type - undefined to help find the problem. why would it be undefined? – Steve Tomlin Jul 24 '23 at 15:29
  • Can you share the code for the `showMessage()` and `selectMessage()` methods? – JBrown Jul 24 '23 at 15:30
  • show message is mainly used for mobile, so it flips between the chat list and the messaging page. And select message just sets the id of the message between two users. This Id is used to fetch the messages – Mat Jul 24 '23 at 15:33
  • If you `console.log()` *inside* `setSelectedUserMessages()` -- Does the first click come back `undefined` as defined in your `selectedUserProps|undefined` Or is it simply empty or null? – Zak Jul 24 '23 at 15:33
  • i just tried this and yes it returns undefined... – Mat Jul 24 '23 at 15:36
  • do you know why it returns undefined? – Mat Jul 24 '23 at 15:38

0 Answers0