0

I have a react child component (FinalReport.js) that is rendering twice, except that on the first render, one of the props is undefined for some reason, which is throwing an error. Of course I could add error handling but that doesn't seem like best practice.

The Parent Component contains user inputs which are saved as a useState Hook (esrData) upon pressing a 'Save' button. The first child component (Airload.js) contains more inputs and calls an API, and saves the result as a useStateHook (airLoadRes). Both hooks are defined in the parent component and passed as props. The child component in question (FinalReport.js) ONLY renders once both hooks become available, and then passes the hooks along. Why is FinalReport rendering twice and why is airLoadRes undefined on the first render? Strict Mode is not being used. Any help is appreciated!

Parent Component

const GenerateEnergySavings = () => {

    const [esrData, setEsrData] = useState();
    const [airLoadRes, setAirLoadRes] = useState();

...

return( ...
// Child Component 2
 {(esrData && airLoadRes != undefined)  ?
         <PDFViewer height='1000px' width='1000px'>
             <FinalReport esrData={esrData} airLoadRes={airLoadRes} />
         </PDFViewer> : ''}
...
// Child Component 1 (API)
<Airload airLoadRes={airLoadRes} setAirLoadRes={setAirLoadRes} />



Child Component 1 EDIT: I should mention this is a bootstrap modal

const Airload = ({ airLoadRes, setAirLoadRes }) => {

...

  // Airload API
    const getAirLoadCalc = async () => {
        console.log(airloadData)
        await Axios.post('https://localhost:44418/airload', airloadData)
        .then(res => {
            setAirLoadRes(res.data)
            console.log(res)
            setKey(6)
        }).catch(err => {
            alert(err)
        })
    }
}

Child Component 2

// This is rendering twice!! ONLY airLoadRes comes in as undefined on first render
export const FinalReport = ({ esrData, airLoadRes }) => {

    console.log(esrData)
    console.log(airLoadRes)

...
Jordan
  • 103
  • 6
  • `(esrData && airLoadRes != undefined)` is probably a typo, you probably meant `(esrData !== undefined && airLoadRes !== undefined)`. Why don't you log what those variables are in the parent component to see what that statement is doing? Also could be a strict mode double render https://stackoverflow.com/questions/61254372/my-react-component-is-rendering-twice-because-of-strict-mode – Andy Ray Aug 11 '22 at 21:09

1 Answers1

0
  1. This code (const [airLoadRes, setAirLoadRes] = useState();) initialize airLoadRes as undefined.

    That's why it is undefined on first render.

  2. React does render on each change of the state, context, or properties. So, I guess FinalReport is rendered twice because of changes on esrData state. Or other state which you possibly have in the code.

Michal Biros
  • 410
  • 1
  • 5
  • 15