1

I am fetching data from MongoDB in my ReactJS app using context API. When I log the data to the web page, I get three arrays instead of one. I am unsure why this is happening.

Here is my code:

In RoomProvider.js file:

I have created a context using React.createContext. In the constructor of RoomProvider, I have initialized state with users, rooms, sortedRooms, featuredRooms, and loading. I am using axios to fetch data from MongoDB in two separate methods - getRooms() and getUsers(). I have a getRoom() method that returns a specific room. In componentDidMount(), I call getRooms() and set loading to false. In the render() method, I am providing the state and getRoom() method to the context provider. In RoomContainer.js file:

I am consuming the context using the withRoomConsumer() higher-order component. I am logging the rooms array to the console. When I run the app, the console shows me an empty array being logged three times, instead of one array. I am unsure why this is happening.

Can someone please help me understand why I am seeing an empty array being logged three times? Here is my code:

(Include the code for RoomProvider.js, RoomContainer.js, and any other relevant files.)

1 Answer 1

1

Seems like its working as expected, you see 3 logs because the component got rendered 3 times.

  1. First render - There is no data because the fetch (in componentDidMount) wasn't triggered yet.
  2. Second render - State was updated (with loading: false) and fetch was triggered, but the call wasn't fulfilled yet, so still no data.
  3. Third render - The data returned and state was updated, now you have the data.
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very mush Sagiv! What is the best way to make the changes I need?
Why do you need to change it? This is a normal behaviour and flow.
Because I want to use the rooms array and display it on the web page. Instead of it I get empty array and I cant display nothing!
But eventually the array is not empty. Asynchronous data fetching is slower than rendering and there's nothing we can do about it. We can handle this by conditionally render the data, maybe showing a loader until we have our data ready for display.
@רועיאנגל if you think you got an answer to your question feel free to accept and mark your question as answered

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.