Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using useContext, the data loads as an empty array first, and when I apply .map() or .find() I get an error message

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?

like image 290
Katerina S Avatar asked Nov 18 '25 10:11

Katerina S


1 Answers

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

like image 67
Sarun UK Avatar answered Nov 20 '25 22:11

Sarun UK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!