0

I want to get all data from firebase database but i dont want UID key to shown, from this code i can get data but it shows uid. I just want to display all the data with this if that's possible

enter image description here

 useEffect(() => { var recentPostsRef = firebase.database().ref('/users'); recentPostsRef.once('value').then((snapshot) => { // snapshot.val() is the dictionary with all your keys/values from the '/store' path console.log(snapshot.val()); }); }, []); 

can i output this data in following manner ?

 { avatar: 'pin-1.png', firstname: 'Mahir', lastname: 'Asrani', latitude: 28.660918, longitude: 77.274468, }, { avatar: 'pin-1.png', firstname: 'name', lastname: 'name', latitude: 00.00066, longitude: 00.275550, }, 

2 Answers 2

1

If you want an array of values, you can use the forEach operator to extract all the values and put them in an array:

recentPostsRef.once('value').then((snapshot) => { let values = []; snapshot.forEach((child) => { values.push(child.val()); }); console.log(values); }); 

Two notes:

  • You are still reading they keys from the database here, just not displaying them anymore. If that is what you want, that is great of course. Just want to make sure you know the keys are still read from the database by the client.

  • It is very common for the app to need the key later, for example to identify a specific set of values, or to update a specific node in the database. You may have to come back to this code later and revisit it to also keep the keys. A simple way to keep both the keys, and values, but keep them separately is:

    recentPostsRef.once('value').then((snapshot) => { let keys = [], values = []; snapshot.forEach((child) => { key.push(child.key); values.push(child.val()); }); console.log(keys, values); // or: setState({ keys: keys, values: values }); }); 
Sign up to request clarification or add additional context in comments.

Comments

1

You can iterate using forEach to retrieve all the data under users:

 useEffect(() => { var recentPostsRef = firebase.database().ref('/users'); recentPostsRef.once('value').then((snapshot) => { snapshot.forEach((childSnap) => { console.log(childSnap.val()); }); }); }, []); 

This will retrieve all the data under the ids, but you can still access the id if you do let uid = childSnap.key

3 Comments

Okay but i want to store all my data in a single state, so i can access it easily. i made this state const [data, setdata] = useState();
why cant you store childSnap.val() inside the state?
i just did it by making an array :) Thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.