How do I convert the firestore data to a JSON object? - javascript

I have these codes:
const App = () => {
const [users, setUsers] = useState();
const getData = async () => {
const citiesRef = firestore.collection("users");
const snapshot = await citiesRef
.where("item.itemName", "==", true)
.where("item", "==", false)
.get();
if (snapshot.empty) {
console.log("No matching documents.");
return;
}
snapshot.forEach((doc) => {
console.log(doc.data());
});
};
useEffect(() => {
getData();
});
return <div>Month</div>;
};
export default App;
If I'll console.log(doc.data()) this is what is shows:
How can I convert this into a JSON object?
I wanted to have a JSON object in order to filter the data. Thank you.

If you are trying to get an array of objects containing all documents' data to filter them, try this:
const usersData = snapshot.docs.map(d => ({id: d.id, ...d.data()}))
// set this array in your state
setUsers(usersData)
This will be an array and you can use methods like filter(), find() as required. For example, to get users having admin role in their roles array:
const admins = usersData.filter(user => user.roles.includes("admin"))

Related

Get firestore data as array

Im tryng to display firestore data but I just get one value. I have try forEach and map. Nothing is working. Heres my code:
React.useEffect(() => {
retrieveNetwork();
}, []);
const retrieveNetwork = async () => {
try {
const q = query(collection(db, "cities", uidx, "adress"));
const querySnapshot = await getDocs(q);
let result = [];
//querySnapshot.docs.map((doc) => setGas(doc.data().home));
querySnapshot.docs.map((doc) => {
result.push(doc.data().home);
setGas(result);
});
} catch (e) {
alert(e);
}
};```
The .map method returns an array (official docs here), so you could do something like this:
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
React.useEffect(() => {
retrieveNetwork();
}, []);
const retrieveNetwork = async () => {
try {
const q = query(collection(db, "cities", uidx, "adress"));
const querySnapshot = await getDocs(q);
// an array from the docs filled only with "home" data
const results = querySnapshot.docs.map((doc) => {
return doc.data().home;
});
// only update the state once per invokation
setGas(results)
} catch (e) {
alert(e);
}
};

How to get specific data from all documents from a collection in firebase?

Platform: React Native (Expo)
So I'm trying to get two values (dotCoins and name) from my firebase db and I can't figure out how to go about it. Here's my firebase structure:
This is what I currently have in place:
// Calling function when screen loads
componentDidMount() {
this.getDotCoins();
this.getUserData();
}
// Calling function when it updates
componentDidUpdate() {
this.getDotCoins();
this.getUserData();
}
// The function
getUserData = async () => {
const querySnapshot = await getDocs(collection(db, "users"));
const tempDoc = [];
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
});
console.log(tempDoc);
};
Both the console.log() prints nothing, and my console remains absolutely empty. I can't find where I'm going wrong since I don't receive any errors too. (I have all packages installed correctly and all functions imported too)
You are not pushing any document data to tempDoc so it'll always be empty. Try refactoring the code as shown below:
getUserData = async () => {
const querySnapshot = await getDocs(collection(db, "users"));
const tempDoc = querySnapshot.docs.map((d) => ({
id: d.id,
...d.data()
}));
console.log(tempDoc);
};
const q = query(collection(db, "users"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.data())
})
});
});
return unsubscribe;

How to get single data based on ID in react firestore v9?

I am unable to get single user data based on using firestore query. Recently, firebase got update to v9 so, i tried to modify query but it's not working may be I am doing something wrong. Here its what i am trying fetch single user based on id.
const id = useParams();
useEffect(() => {
const unsub = onSnapshot(
collection(db, "users", where("id", "==", id)),
(snapShot) => {
snapShot.docs.forEach((doc) => {
console.log(doc.data());
});
},
(error) => {
console.log(error);
}
);
return () => {
unsub();
};
}, [id]);
Collections screenshot
You have to construct your query like this, see docs:
const collectionQuery = query(
collection(db, 'users'),
where('id', '==', id),
);
const unsub = onSnapshot(collectionQuery, (snapshot) => {
...
})
Edit:
Judging from your attached screenshot, you might mean the ID of the document. In this case you can just get the document directly, without a query:
const docRef = doc(db, "users", id);
const snapshot = await getDoc(docRef);

Firestore iterate over an object within a document's data REACT.JS

I'm trying to add some data inside the bookChapters path but it doesn't work, some suggestions?
export const createNewChapter = (bookId, inputText) => {
return async dispatch => {
dispatch(createNewChapterStart());
try {
const chaptersList = [];
firebase
.firestore()
.doc(`Users/${bookId}/bookChapters/${inputText}`)
.onSnapshot(querySnapshot => {
querySnapshot.forEach(doc => {
const chapters = doc.data().bookChapters;
Object.keys(chapters).forEach(k => {
chaptersList.push({ key: k, name: inputText });
});
});
});
dispatch(createNewChapterSuccess(inputText));
} catch (error) {
dispatch(createNewChapterFail(error));
console.log(error);
}
};
};
When you use collection(), it returns a CollectionReference. In this case, it's pointing towards a sub-collection 'bookChapters' but it's a map as in your screenshot. If you want to iterate over that map, you need to fetch that document first and then read the bookChapters field.
const chaptersList = [];
firebase
.firestore()
.doc(`Users/${bookId}`)
.onSnapshot(querySnapshot => {
querySnapshot.forEach(doc => {
const chapters = doc.data().bookChapters
Object.keys(chapters).forEach((k) => {
chaptersList.push({key: k, name: chapters[k]});
})
});
});
It might be better to store the list as an Array if you want to store all chapters in the same doc.
If you were trying to create a sub-collection, you can create one by clicking this button:

How do i retrieve all documents from a collection and its relevant information? (React Native Firebase)

Firebase hierarchy image
I have a collection named "Tickets"
Inside the collection contains many ticketID and its relevant information.
How can I display all the TicketID and the information in each sub ticket??
I am using React Native and Firebase.
Firebase design
I've tried doing this:
firebase.firestore()
.collection("tickets")
.get()
.then(querySnapshot => {
const documents = querySnapshot.docs.map(doc => doc.data())
// do something with documents
console.log(documents);
})
And the result is:
Array []
Right now you are querying for the tickets, and you should be getting their data e.g. the fields for each ticket. But you want data for the ticket's subcollection, 'userTickets'.
You can get data for all 'userTickets' subcollections by using a collection group query:
firebase.firestore()
.collectionGroup('userTickets')
.get()
.then((querySnapshot) => {
const documents = querySnapshot.docs.map((doc) => doc.data());
// do something with documents
console.log(documents);
});
import { AngularFirestore } from '#angular/fire/firestore';
constructor(private db: AngularFirestore) {}
getTickets() {
return this.db.collection('tickets').get().then(querySnapshot => {
const tickets = querySnapshot.docs.map(doc => doc.data())
// you can call getUserTicketsById here to add data from userTicket collection to ticket
// ticktes.forEach(ticket => {const ticketData = this.getUserTicketsById(ticket.id); ticket.userTicket = ticketData})
console.log(tickets);
return tickets;
})
}
getUserTicketsById(userId) {
return this.db.collection(`tickets/${userId}/userTickets`).get().then(querySnapshot => {
const userTickets = querySnapshot.docs.map(doc => doc.data())
// do something with documents
console.log(userTickets);
return userTickets;
})
}

Categories