I am trying to figure out how to get data out of my cloud firestore.
I have given up trying to figure out how to do it with react-firestore-hooks and am just trying to get to the same place as I was able to get to before starting with hooks.
In my old componentDidMount I was able to use this:
async componentDidMount() {
// const fsDB = firebase.firestore(); // Don't worry about this line if it comes from your config.
let options = [];
await fsDB.collection("abs_for_codes").get().then(function (querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, ' => ', doc.data());
options.push({
value: doc.data().title.replace(/( )/g, ''),
label: doc.data().title + ' - ABS ' + doc.id
});
});
});
this.setState({
options
});
Now, the best I am able to do is this:
useEffect(() => {
// fetch data
const unsubscribe = fsDB
.collection("abs_for_codes")
.onSnapshot(({ docs }) => {
setFieldOfResearchesOptions(
// map data to react-select
docs.map(doc => {
const { title } = doc.data();
return {
value: doc.id,
label: title
};
})
);
}, setFieldOfResearchesError);
return () => unsubscribe();
}, [setFieldOfResearchesError, setFieldOfResearchesOptions]);
This generates content that I can use to populate a select menu. The select options list the title field of the data base in the select menu.
What I am trying to get to is what I was able to do to present the select options in the original version.
That is:
Insert a string at the beginning of every value as 'ABS -'
Insert the document id of each document after that string
Then insert the title.
I had this working in the old componentDidMount.
I can't find a way to get that integrated in the current attempt.
Can anyone see how to change the presentation format of the values that get extracted from cloud firestore?
If not wrong, you're calling unsubscribe
when component unmounts so this way will not work. See => https://reactjs.org/docs/hooks-reference.html#useeffect
Try it like this:
useEffect(() => {
let options = [];
await fsDB.collection("abs_for_codes").get().then(function (querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, ' => ', doc.data());
options.push({
value: doc.data().title.replace(/( )/g, ''),
label: doc.data().title + ' - ABS ' + doc.id
});
});
setFieldOfResearchesOptions(options);
});
}, [setFieldOfResearchesError, setFieldOfResearchesOptions]);