Skip to content

Commit

Permalink
Added defensive code to prevent errors when emojis state is empty.
Browse files Browse the repository at this point in the history
  • Loading branch information
xfelipem committed Jul 18, 2019
1 parent e5842a2 commit a34ed3f
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions example/RandomEmoji/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import withTimer from '../../src/withTimer';
// CONSTANTS
const API_URL = 'https://api.github.com/emojis';
const DEFAULT_INTERVAL = 1000;
const EMPTY_STRING = '';

// HELPERS

Expand All @@ -24,9 +25,12 @@ const isObjectEmpty = object => Object.entries(object).length === 0;
* @param {Object} emojis map of emojis links sorted by name.
*/
const selectRandomEmoji = (emojis) => {
if(emojis.length)
const names = Object.keys(emojis);

if (names.length < 1) {
return EMPTY_STRING;
}

return emojis[names[(names.length * Math.random()) << 0]];
};

Expand All @@ -37,7 +41,7 @@ const RandomEmoji = (props) => {

// STATE
const [emojis, setEmojis] = useState({});
const [emoji, setEmoji] = useState('');
const [emoji, setEmoji] = useState(EMPTY_STRING);

// PRIVATE METHODS
const mutateEmoji = () => setEmoji(selectRandomEmoji(emojis));
Expand Down Expand Up @@ -73,7 +77,7 @@ const RandomEmoji = (props) => {
useEffect(fetchEmojisEffectHandler);
useEffect(setTimerEffectHandler);

if (emoji === '') {
if (emoji === EMPTY_STRING) {
return null;
}

Expand Down

0 comments on commit a34ed3f

Please sign in to comment.