Home > Software design >  How do I toggle between connect and connected
How do I toggle between connect and connected

Time:02-01

I have a MySQL Database with an array called connectionList . The array for a user contain several objects with a senderID and receiverID fields and would sometimes be empty if the user has no pending connection request.

I have successfully mapped through the array to fetch out the data to the browser. I am however having issues when I have to use the ifelse statement to make a button toggle between connect if the connectionList array is empty or doesn't contain a senderID that matches the id of the logged in user and connected if the array contains an object having a senderID id that matches the id of the logged in user. I need assistance on what to do.

What I have done

{connectionList && connectionList.map(function (conn){
if(conn.senderID === user.id){
       return <>Connected</>
} else {
       return <>Connect</>
}
})}

CodePudding user response:

You can achieve it by below code

{
        connectionList ?
            <>
                {connectionList.map(conn => {
                    <>
                        {conn.senderID === user.id ?
                            <>Connected</>
                            :
                            <>Connect</>
                        }
                    </>
                })}
            </> 
            :
            <>Connect</>
    }

CodePudding user response:

You can use optional chaining (?.) in combination with some: The .some(conn => conn.senderID === user.id) checks if the callback is true for at least one element in it (in your case at least one connection is from the current user). The ?. is an optional shortcut which returns undefined if connectionList is undefined or will call the method if it's not undefined.

Together this will return <Connected> if at least one connection sender is the current user, else <Connect>.

{
  connectionList?.some(conn => conn.senderID === user.id) ?
    <Connected>
    : <Connect>
}

On a side note: you don't want to use .map except if you want one result per element in the list. In your case you only want one result for the whole list.

  • Related