I am trying to retrieve data from firebase database but am receiving the error mentioned in the title.
I am trying to add a new member from the AddMember.js
component (which works) to firebase.
Now I’m trying to retrieve the data when my dashboard loads in the MembersTable.js
component.
I understand that you can’t map over an object but am i missing something here and how do i solve this?
Below is my code and the screen shot of the data i’m trying to read.
MembersTable.js
const [loading, setLoading] = useState(true);
const [userMembers, setUserMembers] = useState([]);
useEffect(() => {
onAuthStateChanged(auth, (user) => {
console.log(`Welcome to your dashboard.. ${user.uid}`);
// get the data from firebase
const getData = () => {
const dbRef = ref(database, `users/${user.uid}/`);
onValue(dbRef, (snapshot) => {
const data = snapshot.val();
var userMembers = data.members;
console.log(userMembers);
setUserMembers({ userMembers });
setLoading(false);
});
};
getData();
});
}, []);
AddMember.js
const writeMemberToDatabase = (member) => {
const currentUser = auth.currentUser.uid;
const uniqueKey = uuidv4();
const newkey = "hey";
set(child(dbRef, `users/${currentUser}/members/${newkey}`), member)
.then(() => {
console.log(`updated ${currentUser}...`);
setToggle(false);
setMemberDetails([]);
})
.catch((error) => {
console.log("Error adding member to database: ", error);
});
};
const submitForm = (e) => {
e.preventDefault();
console.log("submitted user...");
const member = [
{
membername: memberName,
memberemail: memberEmail,
membershipprice: membershipPrice,
},
];
writeMemberToDatabase(member);
setMemberDetails([...memberDetails, member]);
console.log(auth.currentUser);
};
Please see attached image of my database
2
Answers
I’m not seeing the use of
map
in the code you have provided. What that error typically means is that the variable that you think is an array is actually undefined. That can happen when dealing with asynchronous code, where the value is undefined until the promise resolves. One potential way to handle mapping over a potentially undefined value could be as so…This will map over myVar or if myVar is undefined it will map over the empty array.
i think that the problem is in the setState, the value should be an array but you set as object
setUserMembers({ userMembers });
so try with this
it works if userMembers is array
and last try to don’t use var to declare variables, use let if the value can change or const for functions and values that never changes