Do you know how I can populate the reference Field on a Document using Firestore?
When you create / get a document reference, you can save this into another document. This example is for the Node SDK, but it should give you an idea of how to implement this for Android.
Creating a document reference
// Create the references
let myFirstDoc = db.collection('myCollection').doc();
let mySecondDoc = db.collection('otherCollection').doc();
let batch = db.batch();
// Save the two documents to the batch
batch.set(myFirstDoc, {someData: true});
batch.set(mySecondDoc, {firstDocRef: myFirstDoc});
// Commit the batch
return batch.commit()
.then(response => {
console.log('Data saved');
})
.catch(err => {
console.error(err);
});
Getting an existing reference
return db.collection('myCollection').doc('myDocId')
.then(documentSnapshot => {
let newDoc = db.collection('otherCollection').add({otherDoc: documentSnapshot.ref});
})
.then(response => {
console.log('Data saved');
})
.catch(err => {
console.error(err)
})
Related
I am using react native and firebase realtime database to store and query a list of properties. It seems that when I run the below query in XCode for iOS the array created here shows a list of the property objects. However, when I run this android studio the array is empty. Do you know what may be causing this? Can someone please help here I am very new to react native and using firebase realtime database?
I really do apologies for the poor code formatting:
const array = []
await db.ref(`users/`).on(`value`, snapshot => {
if (snapshot.exists()) {
snapshot.forEach(function(userSnapshot){
if(userSnapshot.hasChild("properties")){
userSnapshot.child("properties").forEach((propertySnapshot) => {
array.push({
key: userSnapshot.key,
property: propertySnapshot.val(),
username: userSnapshot.val().username,
email: userSnapshot.val().email,
phoneNumber: (userSnapshot.val().phoneNumber != null)?userSnapshot.val().phoneNumber:null,
propertyName: propertySnapshot.key,
profile_pic: userSnapshot.val().profile_pic,
connectedAccount_id: (userSnapshot.val().connectedAccount_id != null)?userSnapshot.val().connectedAccount_id:null,
customer: (userSnapshot.val().customer != null)?userSnapshot.val().customer:null,
});
})
}
})
}
});
await database().ref(`users/${auth().currentUser.uid}/your_location`).once(`value`, function(snap){
....
Geocoder.init("******");
Geocoder.from(locationPostcode)
.then(json => {
var location = json.results[0].geometry.location;
global.latitude = location.lat;
global.longtitude = location.lng;
})
.catch(error => console.warn(error));
console.log("array result "+array)
.....
})
The log array shows an array of objects for iOS:
array result [object Object],[object Object],[object Object],[object Object],[object Object]
but for android it's empty:
array result
Hello i'm new with axios and i wanna to display all my data from subpages to screen but I have some trouble because when I display them it shows me the data from the last subpage instead of all of them at the bottom I throw the code how I download the data through axios. How do I display them all ?
const [data, setData] = useState([]);
async function test() {
for (let id = 1; id < 3; id ++) {
axios.get(`https://api.jsonbin.io/b/61f98c361960493ad1865911/${id}`)
.then(({data}) => {
setData(data.commentData)
console.log(data.commentData)
})
.catch((error) => console.error(error))
}
}
useEffect(() => {
test()
}, []);
You are overwriting your data state in each loop, so the last loop iteration is the one that you see.
async function test() {
for (let id = 1; id < 3; id++) {
axios.get(`https://api.jsonbin.io/b/61f98c361960493ad1865911/${id}`)
.then(({ data }) => {
setData(data.commentData) // <-- overwrites previous state
console.log(data.commentData)
})
.catch((error) => console.error(error));
}
}
Use a functional state update to correctly update from the previous state.
async function test() {
setData([]);
for (let id = 1; id < 3; id++) {
axios.get(`https://api.jsonbin.io/b/61f98c361960493ad1865911/${id}`)
.then(({ data }) => {
setData(data => [...data, data.commentData]) // <-- append new data
console.log(data.commentData)
})
.catch((error) => console.error(error));
}
}
You could also map an array of Promises and use Promise.all to get a single array of resolved data values.
async function test() {
const requests = [1,2,3].map(id => axios.get(`https://api.jsonbin.io/b/61f98c361960493ad1865911/${id}`));
try {
const dataArr = await Promise.all(requests);
setData(dataArr.map(({ data }) => data.commentData));
} catch(error) {
console.error(error);
}
}
I am exporting JSON by fetch from the URL. I think I have a binding issue if take from local data file working I'm not completely sure on how I should proceed to bind my function.
Data.js
const Json = require('./one.js'); // not working or const Json = require('./two.json'); // working
export default Json;
one.js
function getvals(){
return fetch('http://xxxxxx')
.then((response) => response.json())
.then((json) => {
return json.products;
})
.catch((error) => {
console.error(error);
});
}
getvals().then(response => response);
two.json
[{"id":"1","category":"kkk","title":"sss"}]
Nothing in one.js exports anything. With CommonJS-style modules, you export something by assigning it to a property on exports (or by reassigning the exports variable entirely).
But note that since what you're getting is only available asynchronously, other modules may request one.js's default export before the asynchronous process has completed. The usual solution to that is export the promise from fetch:
module.exports = fetch('http://xxxxxx')
.then((response) => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then((data) => {
return data.products;
});
Also note that you need to check for HTTP success (the footgun in the fetch API) and you don't want to hide errors; let the users of the module know if the fetch fails.
Code using that would need to use the promise, e.g.:
require("./one.js")
.then(data => {
// ...use the products...
})
.catch(error => {
// ...handle the fact the fetch failed and the data won't be coming...
});
I don't know the React Native ecosystem, but if you can to switch to JavaScript modules ("ESM" = ECMAScript Modules) instead (and if you want to), someday you'd be able to use a new feature called top-level await. The V8 engine has it (behind a flag), presumably JavaScriptCore will at some stage. That would let you suspend module evaluation until the fetch completed, and directly export the result:
// With top-level `await` in an ESM module
export default await fetch('http://xxxxxx')
.then((response) => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then((data) => {
return data.products;
});
Modules using it would be able to get the products directly:
import products from "./one.js";
If you're using Webpack (again, I don't know the React Native ecosystem), it has experimental support for it, too.
I want to use the data from JSON.stringify that I save locally from async storage, so I can manage them locally (like user data for login)
I already save it to AsyncStorage
componentDidMount = async () => {
fetch('My_url', {
method: 'GET'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
}
saveData = async () => {
try {
await AsyncStorage.setItem('user', JSON.stringify(this.state.data));
Alert.alert('Saved', 'Successful');
} catch (error) {
Alert.alert('Error', 'There was an error.')
}
this is the JSON
0
username "admin2"
password "*****"
access "1"
name "dwi"
phone_number "087613721"
email "**#****.com"
score null
status "0"
1
username "admin3"
password "***"
access "1"
name "Satria"
phone_number "****"
email "*****3#*****.com"
score null
status "0"
and I try to get the value using this, but can't show anything in node console.log, it said "unidentified" (i just using press button on this)
displayData = async ()=>{
try{
let user = await AsyncStorage.getItem('user');
let parsed = JSON.parse(user);
console.log(parsed.email);
}
catch(error){
alert(error)
}
}
can some JSON parser output use like to be database function?
like for login so we can log in and check the data user from json.parser that I store in the data using async storage?
or output some data that we want to be used like in where statement in the SQL ?
The response of await AsyncStorage.getItem('user'); is an array like [key,value].
You need write parsed[0] to get key and JSON.parse(parsed[1]) to get json value.
So I'm using the most recent version of Ionic2 (v3.4) and I'm trying to get the ionic native SQLite to work. I've been able to create database file and put a table in it like so:
this.sqlite.create({
name: "data.db",
location: "default"
})
.then((db:SQLiteObject) => {
db.executeSql(tableQuery, {})
.then(() => console.log("success"))
.catch(() => console.log("fail"));
})
Inserting works too. But when I try to get the result of a selection:
this.sqlite.create({
name: "data.db",
location: "default"
})
.then((db:SQLiteObject) => {
db.executeSql("SELECT * FROM savedCoupons where itemId=" + itemId, {})
.then((db) => {console.log(JSON.stringify(db))})
.catch(() => console.log("***ERROR WITH SELECT***"));
})
.catch(() => console.log("ERROR: FAILED TO CREATE/OPEN DATABASE."));
I get lost because of the lack of documentation. JSON.stringify() is being run so it would seem the query worked. It returns {"rows":{"length":1}, "rowsAffected":0} and that's it. How do I access the result of the query?
Let you have three columns e.x id,name,lastname in your table.
after querying you can access it like:
db.executeSql('SELECT * FROM student WHERE id='+1, {})
.then(result => {
for (var i = 0; i < result.rows.length; i++) {
console.log("---Id---"+result.rows.item(i).id);
console.log("---Name---"+result.rows.item(i).name);
console.log("---Lastname---"+result.rows.item(i).lastname);
}
});