I have the following code in a functional component:
const [ folder, setFolder ] = useState([]);
const folderData = useContext(FolderContext);
const folderId = props.match.params.id;
useEffect(() => {
retrieveData()
}, [folder])
const retrieveData = () => {
const findFolder = folderData.find(f => f.id === folderId);
console.log(findFolder);
setFolder(findFolder);
}
When I console.log(folder) I get three instances of undefined, undefined, then one with the data I need in it. If I try to access the data inside of folder such as folder.name, I get this error message: TypeError: Cannot read property 'name' of undefined.
How can I get the functions to only render after all the data is loaded?
Initial render you can't avoid. If you are getting the data from the server, the initial load will be undefined, and incase you are not handing the null checks, will get the error.
One approach would be to handle the null case.
Or you want to load your component once you receive the data, you might have to use React.Suspense
Suspense will give a fallback until your component receives the response. In fallback we can include the loader image so that user will see the loader image until the data loads.
Read more - https://reactjs.org/docs/concurrent-mode-suspense.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With