@@ -27,7 +27,6 @@ const UsageBar: React.FC<Props> = ({
2727 total,
2828 items,
2929} ) => {
30- const [ usedColors , setUsedColors ] = React . useState < string [ ] > ( [ ] )
3130 const [ formattedItems , setFormattedItems ] = React . useState < Item [ ] > ( [ ] )
3231
3332 const lightColors : string [ ] = React . useMemo ( ( ) => {
@@ -70,41 +69,38 @@ const UsageBar: React.FC<Props> = ({
7069 )
7170
7271 /**
73- * Push a background color in the usedColors array to provide a color
74- * to elements that don't have it.
72+ * Formats the items prop array providing a color to
73+ * elements without a defined one
7574 */
76- const setColors = React . useCallback ( ( ) => {
75+ const formatItemsArray = React . useCallback ( ( ) => {
7776 let selectedColors : string [ ] = [ ]
7877 const colorsToPickFrom = darkMode ? darkColors : lightColors
7978
8079 // For each element a random index is generated and then used to pick a value
81- // from the colors array; the selected value is removed by its original array
82- // and it's pushed into the usedColors one.
80+ // from the colorsToPickFrom array; the selected value is removed by its original array
81+ // and it's pushed into the selectedColors one.
8382 for ( let i = 0 ; i < items . length ; i ++ ) {
84- const randIndex = Math . floor ( Math . random ( ) * items . length )
83+ const randIndex = Math . floor ( Math . random ( ) * colorsToPickFrom . length )
8584 const color = colorsToPickFrom [ randIndex ]
8685 selectedColors . push ( color )
8786 colorsToPickFrom . splice ( randIndex , 1 )
8887 }
89- setUsedColors ( selectedColors )
90- } , [ items , darkMode ] )
91-
92- React . useEffect ( ( ) => {
93- if ( uncorrectValues ) return
94- setColors ( )
95- } , [ items ] )
9688
97- React . useEffect ( ( ) => {
98- if ( uncorrectValues ) return
89+ // Each element from the items array is formatted correctly
90+ // with a defined and valid color property.
9991 setFormattedItems (
10092 items . map ( ( item : Item , index : number ) => {
101- if ( item . color ) return item
102- else return { ...item , color : usedColors [ index ] }
93+ return ! ! item . color ? item : { ...item , color : selectedColors [ index ] }
10394 } )
10495 )
105- } , [ items , usedColors ] )
96+ } , [ items , darkMode ] )
97+
98+ React . useEffect ( ( ) => {
99+ if ( uncorrectValues ) return
100+ formatItemsArray ( )
101+ } , [ items ] )
106102
107- const renderUsageBar = ( ) => {
103+ const renderUsageBar = React . useMemo ( ( ) => {
108104 if ( compactLayout ) {
109105 return (
110106 < div
@@ -183,15 +179,15 @@ const UsageBar: React.FC<Props> = ({
183179 </ div >
184180 </ div >
185181 )
186- }
182+ } , [ formattedItems ] )
187183
188184 if ( uncorrectValues )
189185 return (
190186 < span className = "u-UsageBar__error" >
191187 ERROR: Elements values exceed the total.
192188 </ span >
193189 )
194- return renderUsageBar ( )
190+ return renderUsageBar
195191}
196192
197193export default UsageBar
0 commit comments