add, set, update document with geofirestore - reactjs

I am trying to use geofirestore https://geofirestore.com/ with react native, the fact is that I have already implemented the methods to add elements in firestore, however I have read in the documentation that the data have to be added by geofirestore methods. Do I have to change all the methods and use the firestore methods? I use javascript and not typeScript, I see that there are examples with typescript and it seems that they have updated the library and other examples do not work.
How could I add elements in the bbdd?
I used geofirex and it was very simple but it has no limit, I want to change to geofirestore to be able to use this feature.
Thank you!

so most if not all of the Typescript examples are almost identical to what you would do in JS (as well as the regular firebase library). Let me give you an example of adding and querying (with a limit) in react-native-firebase.
import firebase from 'react-native-firebase';
const doc = {
coordinates: new firebase.firestore.GeoPoint(0, 0),
name: 'The center of the WORLD'
};
const collection = firebase.firestore().collection('todos');
collection.add(doc).then((docRef) => {
collection.limit(100).get().then((querySnapshot) => {
// 100 items in query
querySnapshot.docChanges.forEach((change) => {
console.log(change.doc);
});
});
});
Now I've never used RNF, but from the docs I can gather that this is correct, and they do almost everything the same as the JS Firebase library (except docChanges returns as an array rather than a function that returns an array...). Anyway, lets see the same thing in Geofirestore with the added benefit of querying with limit and near a location!
import firebase from 'react-native-firebase';
import { GeoFirestore } from 'geofirestore';
const doc = {
coordinates: new firebase.firestore.GeoPoint(0, 0),
name: 'The center of the WORLD'
};
const geofirestore = new GeoFirestore(firebase.firestore());
const geocollection = geofirestore.collection('todos');
geocollection.add(doc).then((docRef) => {
geocollection.limit(100).near({
center: new firebase.firestore.GeoPoint(0, 0),
radius: 10
}).get().then((querySnapshot) => {
// 100 items in query within 10 KM of coordinates 0, 0
querySnapshot.docChanges().forEach((change) => {
console.log(change.doc);
});
});
});
Anyway, don't be afraid of the Typescript code samples, if you just strip the : GeoFirestore or whatever it's valid JS...
// This in TS
const firestore = firebase.firestore();
const geofirestore: GeoFirestore = new GeoFirestore(firestore);
// Is this in JS
const firestore = firebase.firestore();
const geofirestore = new GeoFirestore(firestore);
Finally I try to keep this viewers app up to date with Vanilla JS, if that helps.

This works perfectly
await eventRef.update({'d.arrUsers':
firebase.firestore.FieldValue.arrayUnion(userUid)});
However I am unable to make this work, it is a map and I want to add another user, before it worked correctly...
await eventRef.set({'d.userMap': {
[userUid]: {
name: name,
age: age
}
}}, {merge: true});
If I use update it deletes the one that exists and puts the new one, if I do so it gets it out of d in the document

Related

I want to update firebase database with react

I have a problem while trying to update data in the firebase database with my react code.
Most probably my code syntax is not good, so can you help me in some way?
This is my code syntax:
const addNewData = async (e) => {
e.preventDefault();
let data = {
sifra:sifraRef.current.value,
naziv:nazivRef.current.value,
detalji_dijete:detaljiRef.current.value,
opis:opisRef.current.value,
broj_obroka:brojObrokaRef.current.value,
napomena:napomenaRef.current.value
}
const uuid = uid();
await updateDoc(collection(db, `namirnice/${uuid}`), data)
close();
}
All these examples I saw on youtube tutorials works...
I hope you can help me.
The updateDoc function is used to update an existing document. But since you call uuid(), you always get a new value and so you're trying to update a document that doesn't exist yet, which isn't possible.
To create a new document, use setDoc instead of updateDoc in your code.
Also see the Firebase documentation on setting a document

Vue Fetch Behaving differently on Local vs. Deployed

I feel that I am implementing Vuex Store or async-await incorrectly.
My goal is to pull a set of badges (we call them patches) from my content management service. I need the list to be up to date whenever a new badge is added in the future (which will be infrequent but not never). I don't know how to make a check that will refresh the list whenever the current badge count is different from the number of badges in the cms but that is beside the current problem.
I have an array, rawPatches, in Vuex that should only be built if rawPatches.length <= 0. Once built it should have 60 items pulled from my content management service. This seems to work fine when I do npm run dev on my local machine. However, once pushed to the development site and compiled through Netlify, the array is messed up. When I visit another page and come back to where the length check is the array has an extra 60 items. So when I leave and come back twice then the array has 180 items, and so on and so forth. Also, when I close the window and then come back the incorrect count remains. I guess this means that the Vuex State is cached? I don't know if the length check doesn't get executed or if the array doesn't exist when the check happens but then does exist when new items are added because I'm awaiting the build function. I really have no idea what is going on but I have been trying to sort it out for a few months and am ripping my hair out.
I am using async-await because readPersonalPatches relies on the patches being in Vuex Store.
index.js
export const state = () => ({
rawPatches: [],
});
export const mutations = {
addToArray: (state, payload) => {
state[payload.arr].push(payload.value);
},
}
export const actions = {
async readPatches({ commit, state }) {
console.log('inside of readPatches', state.rawPatches.length);
const patches = await this.$content('patches').fetch();
patches.forEach((patch) => {
commit('addToArray', { arr: 'rawPatches', value: patch });
if (patch.categories) {
if (
JSON.stringify(patch.categories).includes('orbit') ||
JSON.stringify(patch.categories).includes('point')
) {
commit('addToArray', { arr: 'geographicPatches', value: patch });
}
}
if (patch.isSecret) {
commit('addToArray', { arr: 'secretPatches', value: patch });
}
});
console.log('After adding patches', state.rawPatches);
},
}
header component
async fetch() {
console.log('Does this work?');
try {
console.log('length', this.rawPatches.length <= 0);
if (this.rawPatches.length <= 0) {
await this.readPatches({ context: this.$nuxt.context });
}
this.readPersonalPatches();
} catch (error) {
console.log(error);
}
},
Locally, the console reads:
Does this work?
length true
inside of readPatches 0
after reading patches [...]
However, the console is blank on the dev server.
Thank you for any help with this!!

Querying persisted React WYSIWYG data from MongoDB

thanks in advance!
In summary, I am using React's WYSIWYG rich text editor, and saving the text written in the editor to a MongoDB, data is sent to a server which does the insertion. My issue is that I am unable, after following recommended code, to retrieve the stored data back successfully to display it on my page. This is for a prospective blog post site.
Below I've provided all relevant code:
My Component which sends the data to the server to insert it into MongoDB, (not in order, only relevant code):
<Editor
editorState={editorState}
onEditorStateChange={handleEditorChange}
wrapperClassName="wrapper-class"
editorClassName="editor-class"
toolbarClassName="toolbar-class"
/>
const Practice = () => {
const [editorState, setEditorState] = useState(
() => EditorState.createEmpty(),
);
const [convertedContent, setConvertedContent] = useState(null);
const handleEditorChange = (state) => {
setEditorState(state);
convertContentToRaw();
}
const convertContentToRaw = () => {
const contentState = editorState.getCurrentContent();
setEditorState(editorState: {convertToRaw(contentState)});
}
const stateToSend = JSON.stringify(editorState);
try {
const response = await axios.post('http://localhost:8080/api/insert', {
content: stateToSend
})
} catch(error) {
}
In MongoDB, I've initialized 1 column for storing the WYSIWYG data, I've initialized as an empty JS object:
const wysiwygtest = new mongoose.Schema({
content: {
type: {}
}
});
As a result, my data is inserted into MongoDB as such, with everything desired clearly in data type such as RGBA etc. correct me if I'm wrong but I believe Mongo uses BSON, a form of binary based JSON, so this looks doable for retrieval:
Lastly, the code which is not working correctly, the retrieval. For this, I have no interest just yet in placing the data back into the text editor. Rather, I'd like to display it on the page like a typical blog post. However, I'm unable to even log to the console as of yet.
I am parsing the data back to JSON using JSON.parse, converting JSON to JS object using createFromRaw and using EdiorState (even though I don't have the text editor in this component but this seems to be needed to convert the data fully..) to convert fully:
useEffect( async () => {
try {
const response = await axios.get('http://localhost:8080/api/query', {
_id: '60da9673b996f54d507dbfc5'
});
const content = response;
if(content) {
const convertedContent =
EditorState.createWithContent(convertFromRaw(JSON.parse(content)));
console.log('convertedContent - ', convertedContent);
}
console.log('response - ', content);
} catch(error) {
console.log('error!', error);
}
}, [])
My result for the past day and last night has been the following:
"SyntaxError: Unexpected token o in JSON at position 1" and so I'm unsure what I'm doing wrong in the data retrieval, and possibly even the insertion.
Any ideas? Thanks again!
Edit: For more reference, here is what the data looks like when output to the console without a JSON.stringify, this is the full tree of data. I can see all of the relevant data is there, but how do I convert this data and display it into a div or paragraph tag, for example?
More or less figured this out, see my solution below given the aforementioned implementation:
Firstly, I think my biggest mistake was using JSON.parse(); I did away with this with success. My guess as to why this does not work (even though I inserted into MongoDB as JSON) is because we ultimately need the draft-js.Editor Object to convert the data from the DB into an object type it can understand, in order to subsequently convert into HTML successfully, with all properties.
Below is the code with captions/descriptions:
Retrieve data (in useEffect before React component is rendered:
useEffect( async () => {
console.log('useeffect');
try {
const response = await axios.get('http://localhost:8080/api/query', {
_id: '60da9673b996f54d507dbfc5' //hard-coded id from DB for testing
});
const content = response.data; //get JSON data from MongoDB
if(content) {
const rawContent = convertFromRaw(content); //convert from JSON to contentstate understood by DraftJS, for EditorState obj to use
setEditorState(EditorState.createWithContent(rawContent)); //create EditorState based on JSON data from DB and set into component state
let currentContentAsHTML = draftToHtml(convertToRaw(editorState.getCurrentContent())); //create object which converts contentstate understood by DraftJS into a regular vanilla JS object, then take THAT and convert into HTML with "draftToHtml" function. Save that into our 2nd state titled "convertedContent" to be displayed on page for blog post
setConvertedContent(currentContentAsHTML);
}
} catch(error) {
console.log('error retrieving!', error);
} },[convertedContent]) //ensure dependency with with convertedContent state, DB/server calls take time...
In component render, return HTML which sets the innerHTML in the DOM using/passing the convertedContent state which we converted to proper HTML format in step 1.
return (
<div className="blog-container" dangerouslySetInnerHTML={createMarkup(convertedContent)}></div>
</div>
);
In step 2, we called a function entitled, "createMarkup"; here is that method. It essentially returns HTML object using the HTML converted data originally from our database. This is a bit vulnerable it terms of malicious users being able to intercept that HTML in the DOM, however, so we use a method, "purify" from "DOMPurify" class from 'isomorphic-dompurify" library. I'm using this instead of regular DOMPurify because I am using Next JS and NEXT runs on the server side as well, and DOMPurify only expects client side:
const createMarkup = (html) => {
return {
__html: DOMPurify.sanitize(html)
}
}

MongoDB Webhook function to save forminput in database

I've been trying to save data from my form in my MongoDB for some time.
I also get a response from the database.
See also: create object in mongo db api onclick sending form
Unfortunately there are not enough tutorials in my mother tongue and I don't seem to understand everything in English.
I've tried some of the documentation, but I always fail.
What is missing in my webhook function so that the form data can be stored?
exports = function(payload) {
const mongodb = context.services.get("mongodb-atlas");
const mycollection = mongodb.db("created_notifications").collection("dpvn_collection");
return mycollection.find({}).limit(10).toArray();
};
The Webhookfunction was totally wrong.
READ THE DOCUMENTATION FIRST
exports = function(payload, response) {
const mongodb = context.services.get("mongodb-atlas");
const requestLogs = mongodb.db("created_notifications").collection("dpvn_collection");
requestLogs.insertOne({
body: EJSON.parse(payload.body.text()),
query: payload.query
}).then(result => {
})
};

Uploading an image to Azure Blob Storage using React

I want to upload an image to Azure Blob Storage using React.
I've tried a lot of examples and none of them work.
The one that seemed the best was this one but still didn't manage to get it working on React.
What I'm trying right now is to use the createContainerIfNotExists method just to test and the error is Cannot read property createBlobServiceWithSas of undefined
My code is the following:
import AzureStorage from 'azure-storage';
const account = {
name: 'x',
sas: 'x',
};
const blobUri = `https://${account.name}.blob.core.windows.net`;
const blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, account.sas);
export const createContainer = () => {
blobService.createContainerIfNotExists('test', (error, container) => {
if (error) {
// Handle create container error
} else {
console.log(container.name);
}
});
};
export default createContainer;
According to my research, because you develop A React application, we can not use the createBlockBlobFromBrowserFile method. We just can use the method in the browser. For more details, please refer to the document.
According to the situation, I suggest you use the other method(such as uploadStreamToBlockBlob) to upload image with V10 sdk. For more details, please refer to https://learn.microsoft.com/en-us/javascript/api/#azure/storage-blob/?view=azure-node-latest

Resources