chocalaca
chocalaca

Reputation: 406

React: adding ternary operator for component breaks progress bar

I am still learning React and am trying to parse text from an API call into json objects while displaying progress in a progress bar.

Below, Home.js uses useEffect hook to

Finally, seriesIdParts is passed to Occupation.js as props. That works fine and working code is displayed below.

My problem is that I want to make the progress bar disappear when parseText is finished. I found a post that did it using a ternary operator, so trying that I changed this:

<ProgressBar percentage={percentage}/> 

to this:

{percentage >= 100 ? console.log("Done.") : <ProgressBar percentage={percentage}/> 

and now the progressBar disappears, but it no longer populates green. I can log the percentage value just fine in both ProgressBar.js and Filler.js, so it seems to be that the Filler width element is not picking up the percentage value increment:

<div className="filler" style={{ width: `${percentage}%`}}>

How do I fix this?

App.js

import React from 'react';
import './App.css';
import Home from './components/Home';

function App() {
  return (
    <div className="App">
      <Home />
    </div>
  );
}
export default App;

Home.js

import React from 'react';
import { useState, useEffect } from 'react';
import Occupation from './Occupation';
import ProgressBar from './ProgressBar';

const Home = () => {    
    
    const [seriesIdParts, setSeriesIdParts] = useState([]);
    const [percentage, setPercentage] = useState(0);

    async function getData(url) {
        const response = await fetch(url);
        if( response.status !== 200 ) {
            throw new Error('Problem calling ' + url);
        }
        return response.text();
    }

    function parseSeriesId(data) {
        let results = new Set()
        data.forEach(function(value) {     
            let areaCode = value.seriesId.substring(4, 11);
            let industry = value.seriesId.substring(11, 17);
            let occupation = value.seriesId.substring(17, 23);
            let dataType = value.seriesId.substring(23, value.seriesId.length);
            let seriesIdVal = value.value;
            if( dataType === '04') {
                let result = {areaCode: areaCode, industry: industry, occupation: occupation, dataType: dataType, seriesIdVal: seriesIdVal};
                results.add(result);
            }
        })
        return results;
    }
    
    useEffect(() => {
        getData('https://download.bls.gov/pub/time.series/oe/oe.data.0.Current')
        .then(data => {
            const parseText = function(data) {
                data = data.split('\n');
                let localNum = 1090;
                let results = new Set();
                let intervalAmount = 100 / localNum;
                
                for( let i=1; i<=localNum; i++ ) {
                    setPercentage((i * intervalAmount));

                    let line = data[i];
                    if( line !== "") {
                        line = line.split('\t');
                        let seriesIdValue = line[0].trim();
                        let valueValue = line[3].trim();
                        if (valueValue !== '-') {
                            results.add({'seriesId': seriesIdValue, 'value': valueValue});
                        }
                    }
                }
                return results;
            }
            return parseText(data, 100);
        })
        .then(data => {
            return parseSeriesId(data);
        })
        .then(data => {
            setSeriesIdParts(data);
        })
        .catch(err => console.log(err));
    }, [percentage]);

    return(
        <div className="homeComponent">
            <label id="parsetext" >
                Parsing Text...
                <ProgressBar percentage={percentage}/> 
            </label>
            {seriesIdParts && <Occupation seriesIdParts={seriesIdParts}/>}
        </div>
    );
}
export default Home;

ProgressBar.js

import React, { useState } from 'react';
import Filler from './Filler';

const ProgressBar = ({percentage}) => {
    // console.log('Pbar: ', percentage);           <== Displays fine!
   return (  
        <div className="progressbar">
            <Filler percentage={percentage}/>
        </div>
    );
}
export default ProgressBar;

Filler.js

import React from 'react';

const Filler = ({percentage}) => {
    return (  
        <div className="filler" style={{ width: `${percentage}%`}}>
           {console.log('filler: ' + percentage)}.  <== Displays fine!
        </div>
    );
}
export default Filler;

Occupation.js

import React from 'react';
import { useState, useEffect } from 'react';

const Occupation = ({seriesIdParts}) => {
    
    console.log('seriesIdParts in Occupation:', seriesIdParts.size)    <== Displays fine!

    //other code...
};
export default Occupation;

App.css

.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
  }
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.progressbar {
  margin: 4em auto;
  width: 80%;
  height: 2em;
  background-color: lightgray;
  border-radius: 30px;
}

.filler {
  height: inherit;
  width: 0px;
  background-color: green;
  border-radius: inherit;
}

#parsetext {
  text-align: 'center';
  margin: 4em 0 0;
}

UPDATE: If there is a better way to make the progress bar disappear, I'm open to suggestions!

Upvotes: 0

Views: 190

Answers (1)

Lucas Guardado
Lucas Guardado

Reputation: 51

What if you set the height of the filler class to like 20px instead of inherit just to try?

.filler {
  height: inherit;
  width: 0px;
  background-color: green;
  border-radius: inherit;
}

I tried to test just that div and I couldn't see it with "inherit"

Upvotes: 0

Related Questions