skip to Main Content

Let’s start with the client side, here’s the code

//sender function
const getUserMessages = async () => {
    try {
        //new localhost with 'messages'
        const response = await axios.get('http://localhost:8000/messages', {
            params: {userId: userId, correspondingUserId: clickedUserId}
        })
        setUserMessages(response.data)
    } catch (error){
        console.log(error)
    }
}
//receiver function
const getClickedUserMessages = async () => {
    try {
        //new localhost with 'messages'
        const response = await axios.get('http://localhost:8000/messages', {
            params: {userId: clickedUserId, correspondingUserId: userId}
        })
        setClickedUserMessages(response.data)
    } catch (error){
        console.log(error)
    }
}

useEffect(()=>{
    getUserMessages()
    getClickedUserMessages()
}, [])

The infinite request is from the http://localhost:8000/messages. Although, I give dependency in useEffect(), but it keeps looping. I can’t find what causes this issue. Here’s the server side of /messages. I use Mongo database.

app.get('/messages', async (req, res)=> {

const {userId, correspondingUserId} = req.query
const client = new MongoClient(uri)

try{
    await client.connect()
    const database = client.db('jassy-data')
    const messages = database.collection('messages')

    const query = {
        from_userId: userId, to_userId: correspondingUserId
    }
    const foundMessages = await messages.find(query).toArray()
    res.send(foundMessages)
} finally {
    await client.close()
}
})

const descendingOrderMessages = messages?.sort((a, b) => a.timestamp.localeCompare(b.timestamp))

return (
    <>
        <Chat descendingOrderMessages={descendingOrderMessages}/>          
        <ChatInput
            user={user}
            clickedUser={clickedUser}
            getUserMessages={getUserMessages()}
            getClickedUserMessages={getClickedUserMessages()}

        />
    </>
)

Is there something wrong, may I need more source?

2

Answers


  1. Chosen as BEST ANSWER

    The problem was in the < ChatInput /> when I assign the value to the function, the function name got attached with the parentheses. The correct one is here.

    <ChatInput
            user={user}
            clickedUser={clickedUser}
            //Notice there is no (parentheses) next to the function var name
            getUserMessages={getUserMessages}
            getClickedUserMessages={getClickedUserMessages}
    
        />
    

  2. There is nothing to loop except db connection. Check url to db. console.log after

    await client.connect()
    

    I guess its stuck on this await

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search