Search code examples
javascriptreactjsreact-hooksuse-effect

How do I handle this useEffect issue where a variable is referenced before getting set


Ok so I have some columns that i'm setting data for but the data takes a sec to get prepared so i'm running into an issue where sometimes things are ready and sometimes they're not. I'm using 2 useEffect s but I feel like i'm doing something wrong. Here is an example of what i'm talking about

So pretty much sometimes my values for the lodash stuff isn't getting set before the app tries to populate the columns. Otherwise this is working fine, its just the order of operations on the setting of the stuff is like hit or miss. I think theres probably a better way to set the variables from the template. The error I'm getting about every 1/10 times is TypeError: Cannot read property 'name' of undefined because its trying to set the type's render text but it hasn't been assigned so it errors out and just keeps erroring until I reload the page.


Solution

  • Try adding optional chaining

    types[rowData.cardTypeId]?.name
    

    Or

    Make a loader, so once two apis got resolved show the table.

    !loading && <Table />
    

    And in your useEffect setLoader(true), when api call starts and when either in .then or .catch make setLoader(false)

    Hope this will give you a better understanding