I am using Firebase in this component to retrieve an array of some basic user details. The array size is always 3 with this query. The function that carries out this action is whoToFollow() and when the results are received the function updates a state variable 'who' There is no array mutation happening here. I simply reset the state to the returned value. Unfortunately despite confirming that the state has indeed been updated, the component does not re-render to display this. In order to simplify the code I have only used the length of the array as the value to be displayed.
Below the code I have included a screenshot of the console logs which display the code execution steps and shows a confirmation of the state value being changed. (returned data is made up test data)
const storage = getStorage(firebaseApp);
const db = getFirestore();
function Aside() {
const [who, setWho] = useState([])
const whoToFollow = async () => {
const usersRef = collection(db, "users");
const q = query(usersRef, limit(3));
const querySnapshot = await getDocs(q);
const results = await querySnapshot.docs.map(doc => doc.data());
let filteredArray = []
results.forEach(async (user) => {
let imgPath = await getDownloadURL(ref(storage, user.profilePicture));
let tmpObj = {
uid: user.UID,
displayName: user.displayName,
userName: user.userName,
profilePicture: imgPath
};
filteredArray.push(tmpObj);
});
console.log('Users recieved and updating who state')
setWho(filteredArray)
}
useEffect(() => {
console.log('component did mount, calling "WhoToFollow()" function')
whoToFollow()
}, []);
useEffect(() => {
console.log('who state has been updated but nothing is being rendered?')
console.log(who)
}, [who]);
return (
<aside>
<div className='aside-head'>Search</div>
<div className='aside-cont'>
<div className='who-to-follow'>
<div className='wtf-head'>
New users to follow
</div>
<div className='wtf-list'>
{who.length}
</div>
</div>
</div>
</aside>
);
}
export default Aside;