Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/App.css
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@
display: inline-block
}

li {
list-style-type: none;
}

.red {
color: #b22222
}
Expand Down
55 changes: 49 additions & 6 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,62 @@
import React from 'react';
import './App.css';
import React, { useEffect, useState } from 'react';
import ChatLog from './components/ChatLog';
import chatMessages from './data/messages.json';
import './App.css';

const App = () => {

const [chatEntryData, setChatEntryData] = useState([
{
id: 0,
sender: '',
body: '',
timeStamp: '',
liked: false
}
]);

useEffect(() => {
setChatEntryData(chatMessages);
}, []);
Comment on lines +18 to +20

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of using useEffect here to set the values for chatEntryData on page load, you can omit this completely and directly set the state on line 8. That would look like:

  const [chatEntryData, setChatEntryData] = useState(chatMessages);


const [likesCount, setLikesCount] = useState(0);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should always be on the lookout for whether we need to create state or not. Creating additional pieces of state adds complexity to a project. When possible, we should prefer to calculate values instead of using state to keep track of it.

To remove the state likesCount you'd need to have a method like calculateLikesCount that iterates over chatEntryData and adds up the likes from each message:

const calculateLikesCount = (chatEntryData) => {
    return chatEntryData.reduce((total, message) => {
      return message.liked ? (total += 1) : total;
    }, 0); 
};


const updateChatEntryData = updatedEntry => {
const updatedEntries = chatEntryData.map(entry => {
if (entry.id === updatedEntry.id) {
if (updatedEntry.liked === true) {
setLikesCount((likesCount) => likesCount + 1);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the total number of likes can be found without introducing state, this line can be removed.

return updatedEntry;
} else {
setLikesCount((likesCount) => likesCount - 1);
return updatedEntry;
}
} else {
return entry;
}});
setChatEntryData(updatedEntries);
};

return (
<div id="App">
<header>
<h1>Application title</h1>
<h1>Rockin' React Chat Log!</h1>
<h2>{likesCount} ❤️</h2>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of using likesCount here, you'd invoke your helper method that calculates the likes

<h2>{calculateLikesCount()} ❤️</h2>

</header>
<main>
{/* Wave 01: Render one ChatEntry component
Wave 02: Render ChatLog component */}
<div className="messageContainer">
<div>
<ul>
<ChatLog
entries={chatEntryData}
onUpdateLikes={updateChatEntryData}
></ChatLog>
</ul>
</div>
</div>
</main>
</div>
);
};

export default App;
export default App;
2 changes: 1 addition & 1 deletion src/App.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ describe('Wave 03: clicking like button and rendering App', () => {
fireEvent.click(buttons[10])

// Assert
const countScreen = screen.getByText(/3 ❤️s/)
const countScreen = screen.getByText(/3 ❤/)
expect(countScreen).not.toBeNull()
})

Expand Down
38 changes: 31 additions & 7 deletions src/components/ChatEntry.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,46 @@
import React from 'react';
import React, { useState } from 'react';
import TimeStamp from './TimeStamp';
import './ChatEntry.css';
import PropTypes from 'prop-types';

const ChatEntry = (props) => {

const [isMessageLiked, setIsMessageLiked] = useState(false)


const toggleLikeButton = (event) => {
const updatedChatEntry = {
id: props.id,
sender: props.sender,
body: props.body,
timeStamp: props.timeStamp,
liked: !props.liked
}
setIsMessageLiked(!isMessageLiked);
props.onHandleLikes(updatedChatEntry);
};
Comment on lines +11 to +21

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're already keeping track of chatEntryData in app.js (updateChatEntryData on line 24) so we should keep all chatEntryData logic in app.js instead of having it in different components which makes the code hard to maintain. It's easier to remember that everything is in app.js (instead of having to check each component to see if make changes to chatEntryData). In industry, an application could have hundreds of components so keeping logic organized is important.

We also discussed lifting up state in the Learn readings. Here, we can lift up the like state out of ChatEntry and into App.js to follow this pattern of lifting state up.

This means toggleLikeButton should live in app.js and get passed down to ChatEntry as a prop. So you'd have a method like toggleLike in app.js:

const toggleLike = (id) => {
    setChatData((chatData) =>
    chatData.map((message) => {
      if (message.id === id) {
        return {...message, liked: !message.liked};
      } else {
        return message;
      }
    })
    );
  };

and then your onClick event handler on line 29 below would look like:

onClick={() => props.toggleLike(props.id)}


return (
<div className="chat-entry local">
<h2 className="entry-name">Replace with name of sender</h2>
<h2 className="entry-name">{props.sender}</h2>
<section className="entry-bubble">
<p>Replace with body of ChatEntry</p>
<p className="entry-time">Replace with TimeStamp component</p>
<button className="like">🤍</button>
<p>{props.body}</p>
<p><TimeStamp time={props.timeStamp}></TimeStamp></p>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice use of the provided TimeStamp component to properly display the time

<button className="like" onClick={toggleLikeButton}>
{props.liked ? '❤️' : '🤍'}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

</button>
</section>
</div>
);
};

ChatEntry.propTypes = {
//Fill with correct proptypes
id: PropTypes.number,
sender: PropTypes.string,
body: PropTypes.string,
timeStamp: PropTypes.string,
liked: PropTypes.bool,
onHandleLikes: PropTypes.func
};

export default ChatEntry;
export default ChatEntry;
4 changes: 4 additions & 0 deletions src/components/ChatLog.css
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,7 @@
margin: auto;
max-width: 50rem;
}




39 changes: 39 additions & 0 deletions src/components/ChatLog.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import ChatEntry from '../components/ChatEntry';
import PropTypes from 'prop-types';

const ChatLog = (props) => {

const fullChatLog = props.entries.map((entry, index) => {
return (
<li key={index}>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should only use index for the key prop when we do not have an object ID, use index as a last resort. Since you have entry.id, use that id for key instead here

<ChatEntry
id={entry.id}
sender={entry.sender}
body={entry.body}
timeStamp={entry.timeStamp}
liked={entry.liked}
onHandleLikes={props.onUpdateLikes}
></ChatEntry>
</li>
)
});

return (
<div className="fullChatLog">
{fullChatLog}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While Learn does show using a variable to reference the return value from calling .map() and then using the variable in the JSX like you've done here, I did want to call out that you'll see another, more common way of writing code that iterates over a list of objects:

return (
    <ul>
        {props.entries.map.((entry, index) => {
            <li key={index}>
            <ChatEntry
                id={entry.id}
                sender={entry.sender}
                body={entry.body}
                timeStamp={entry.timeStamp}
                liked={entry.liked}
                onHandleLikes={props.onUpdateLikes}>
            </ChatEntry>
            </li> 
            }
        }
)

</div>
)
};

ChatLog.propTypes = {
entries: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number,
sender: PropTypes.string,
body: PropTypes.string,
timeStamp: PropTypes.string,
liked: PropTypes.bool
})),
onUpdateLikes: PropTypes.func
};

export default ChatLog;
7 changes: 6 additions & 1 deletion src/components/TimeStamp.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { DateTime } from 'luxon';
import PropTypes from 'prop-types';

const TimeStamp = (props) => {
const time = DateTime.fromISO(props.time);
Expand All @@ -8,4 +9,8 @@ const TimeStamp = (props) => {
return <span title={absolute}>{relative}</span>;
};

export default TimeStamp;
TimeStamp.propTypes = {
time: PropTypes.string
}

export default TimeStamp;
18 changes: 9 additions & 9 deletions src/data/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -159,33 +159,33 @@
"body":"so you are a robot",
"timeStamp":"2018-05-29T23:13:31+00:00",
"liked": false
},
{
},
{
"id": 24,
"sender":"Estragon",
"body":"NO, I am a human, you are a robot.",
"timeStamp":"2018-05-29T23:14:28+00:00",
"liked": false
},
{
},
{
"id": 25,
"sender":"Vladimir",
"body":"but you just said that you are robots",
"timeStamp":"2018-05-29T23:15:47+00:00",
"liked": false
},
{
},
{
"id": 26,
"sender":"Estragon",
"body":"No, I said you are a person, I am a robot.",
"timeStamp":"2018-05-29T23:16:53+00:00",
"liked": false
},
{
},
{
"id": 27,
"sender":"Vladimir",
"body":"then you are lying",
"timeStamp":"2018-05-29T23:17:34+00:00",
"liked": false
}
}
]