Skip to content

Instantly share code, notes, and snippets.

@pushkar100
Created May 1, 2022 20:21
Show Gist options
  • Select an option

  • Save pushkar100/7d284f7e7afa8698a9560dedcdc88f77 to your computer and use it in GitHub Desktop.

Select an option

Save pushkar100/7d284f7e7afa8698a9560dedcdc88f77 to your computer and use it in GitHub Desktop.
import React, { useState, useCallback } from "react";
const readStyle = { backgroundColor: "grey" };
const unreadStyle = { backgroundColor: "white" };
const useReadStatusUpdater = (hasRead, onReset) => {
const [read, setRead] = useState(hasRead || false);
const resetRead = useCallback(() => {
setRead(hasRead);
// Handle side effects during a reset!
if (onReset) {
onReset(hasRead);
}
}, [hasRead]);
return {
read,
setAsRead: () => setRead(true),
resetReadStatus: resetRead
};
};
const EmailsListItem = ({ hasRead, onReadStatusChange }) => {
const { read, setAsRead, resetReadStatus } = useReadStatusUpdater(
hasRead,
onReadStatusChange
);
const style = read ? readStyle : unreadStyle;
return (
<div style={style}>
<div>Subject: Email one, Content: Hello</div>
<button
onClick={() => {
/* Renders email content */
setAsRead(true);
}}
>
Open
</button>
<button onClick={resetReadStatus}>Reset read</button>
</div>
);
};
export default EmailsListItem;
/**
* Usage:
* <EmailsListItem onReadStatusChange={() => {}} />
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment