Conditional Rendering /// 1 of 100few ways

Donovan
2 min readAug 20, 2021

Ever been building a single page application using React and get an error similar to, “TypeError: Cannot property “slice” of undefined” whenever you refresh the page?

Error before conditional rendering

I ran into this problem during my time at Flatiron School but I have to admit, I found work arounds while coding my final project that made it work but never fixed the problem. The problem is that React is trying to render a component that is accessing data before your data is available. React does NOT wait to render unless you tell it. Instead of giving the page a set time to wait before render you could tell React to only render that component if a condition is met.

Hence, conditional rendering. My App.js is rendering the Home component. App.js is where I have a useEffect() function that runs a function that fetches data from an endpoint and saves it to my state using redux.

React is trying to render my Home component THEN run useEffect(). Since Home is based on information in state the page will not render since the Home component is triggered before you fetch data from the App.js file.

--

--

Donovan

Learning. Puttin up shots in Angular and Java and Python and anything else I get my hands on. Sights set on becoming a gainfully employed developer.