firebase: don't get data from realtime database - javascript

I don't get data from realtime database, but load is perfect.
how fix it?
const dbRef = database.ref();
var data;
dbRef.child("playlists").child(1).get().then((snapshot) => {
data = snapshot.val();
}).catch((error) => {
console.error(error);
});
data is underfined

There isn't anything wrong in the code but could you try running it this way?
firebase.database().ref("playlists/1").once("value").then((snapshot) => {
console.log(snapshot.val());
}).catch(e => {
console.log(e);
})
Just in case you've share a small part of your code, then there is a typo in the word 'description'. You might want to check if that's the same in your code else it'll log undefined.
Let me know if issue still persists.

Related

Why cant i see any notifications when i send data to device over BLE?

I'm trying to make an app that sends commands to a BLE device and i cant get any feedback. I am using a library called ble.plx which has an option to monitor characteristics but it wont output anything for me.
I need to read values from notifications to use later in my code. This is my first time working with BLE in general so i have no idea what i am doing wrong. I know serviceUUID and characteristicUUID are correct. I am out of ideas.
Here is my code:
function scanAndConnect() {
BLTManager.startDeviceScan(null, null, (error, device) => {
if (error) {
// Handle error (scanning will be stopped automatically)
return
}
// Check if it is a device you are looking for based on advertisement data
// or other criteria.
if (device.name=='Audio PCM Streamer') {
console.log(device.name);
// Stop scanning as it's not necessary if you are scanning for one device.
BLTManager.stopDeviceScan();
device.connect()
.then((device) => {
return device.discoverAllServicesAndCharacteristics()
})
.then( (device) => {
device.monitorCharacteristicForService(SERVICE_UUID,CHARACTERISTIC_UUID,(err,result)=>{
if(err) {
console.log(err)
return;
}
console.log(result);
}); Subscription
device.requestMTU(251)
let data = Uint8Array(9);
data[0]=0xA5;
data[1]=0xA5;
data[2]=0xA5;
data[3]=0xA5;
var b64encoded = btoa(decoder.decode(data));
device.writeCharacteristicWithoutResponseForService(SERVICE_UUID,CHARACTERISTIC_UUID,b64encoded);
})
.catch((error) => {
// Handle errors
});
}
});
}
I did this completely wrong do not use this or try to fix this its just bad.

Firebase push get key with sdk 9 modular approach

As the question asks I'm attempting to get the key after I push to a firebase db.
push(dbRef, formState)
.then((resp) => {
console.log(resp);
})
.catch(error => {
Alert.alert(error)
})
The above console.log gives me the full url of the data pushed. In example:
"https://example.firebaseio.com/organization/asdfasdfasdf/members/-N08ScImBoOckVIRu-AU". I need the key only: `-N08ScImBoOckVIRu-AU`
I incorrectly attempted:
push(dbRef, formState)
.getKey()
.then((resp) => {
})
.catch(error => {
Alert.alert(error)
})
This gives an error.
How can I accomplish this?
If you split the push() call from the actual writing of the data, you can get the key like this:
const newRef = push(dbRef);
console.log(newRef.key);
set(newRef, formState);

Express Server - cannot POST but can GET, mongoDB problem or backend server problem?

I recently deployed my first project, a MERN stack to heroku. However after deployment, I have been met with issues that weren't present in development. A brief explanation of what my web does is that it takes data from mongoDB and allow user to add multiple filters to search through them. It also have the function that allow you to create new data and edit old data. The problem I have is that all function with POST is not working, they would fire but it would have the error of "net::ERR_CONNECTION_REFUSED" and "EditInfo.jsx:58 Error: Network Error at e.exports (createError.js:16)"
at XMLHttpRequest.p.onerror (xhr.js:84)in the network dev tool. However GET works just fine, which means my dynamically generated table would work, but I cannot make new or edit previous data (just as a side note, I cannot generate data for edit although i was able to generate the same data for previously metioned table. I think this is because I'm asking for the data thorough post and for the table through get).I think the issue isn't from MongoDB since GET is working, so my guess would be I need to do some config to allow POST to my server. I'll post some of the function that works and some that doesn't. Any help or lead would be greatly appreciated, Thanks.
Here is one that works:
client side
useEffect(() => {
fetch("/data").then(res => {
if(res.ok) {
return res.json();
} else {
console.error("Cannot asscess data")
}
})
.then(jsonRes => setData(jsonRes))
setError(0)
setShowError(false)
// eslint-disable-next-line react-hooks/exhaustive-deps
},[resetData])
Here is the server
router.route("/data").get((req,res) => {
Disease.find({}, async(err, foundDisease) => {
if(err) {
console.error(err)
} else {
foundDisease.sort(function(a, b){
var nameA=a.diseaseName.toLowerCase(), nameB=b.diseaseName.toLowerCase();
if (nameA < nameB) //sort string ascending
return -1;
if (nameA > nameB)
return 1;
return 0;
});
res.json(foundDisease);}
})
})
Here is one that doens't work:
Here is the client (I use post to get the data because I need to send the id of what info I need)
useEffect(() => {
const idInfo = {id};
axios.post('http://localhost:3001/info', idInfo)
.then(function(res){
setInput({
diseaseName: res.data[0].diseaseName,
species: res.data[0].species,
vector: res.data[0].vector,
vectorName: res.data[0].vectorName,
agent: res.data[0].agent,
agentName: res.data[0].agentName,
symptoms: res.data[0].symptoms,
diagnosis: res.data[0].diagnosis,
treatment: res.data[0].treatment,
prognosis: res.data[0].prognosis,
notes: res.data[0].notes
})
res=null
})
.catch(err => console.error(err))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
Here is the server
router.route("/info").post((req, res) => {
console.log(req.body)
const idInfo = req.body.id;
console.log(idInfo);
current_id = idInfo;
Disease.find({_id: current_id})
.then(foundId => res.json(foundId))
.catch(err => console.error(err));
})
axios.post('localhost:3001/info', idInfo)
You're posting to localhost instead of to the actual deployed server. You should either change this into an environment variable or just put ur heroku address there

How to check existence of a file in Firebase Storage without logging an error?

Basically, I want to check if a file exists on a specific location on FB Storage If so then, do some Stuff else some other stuff needs to be executed.
so far I have tried this
const profile_pic = firebase.storageRef
.child(`profile_pics/${uid}/}`)
.getDownloadURL()
.then((url) => {
setProfileImage(url);
})
.catch((err) => {
// show Default userPic
console.log("err >> ", err);
});
This code Resembles the answer here
This Code works Fine BUT BUT BUT It still logs Error on the console.
All I'm Looking for is the best way to get it done without logging Error On console. Any help is Appreciated! Thanks.
const profile_pic = firebase.storageRef
.child(`profile_pics/${uid}/}`)
.getDownloadURL()
.addOnSuccessListener(new OnSuccessListener(){
{
setProfileImage(url);
})
.catch((err) => {
console.log("err >> ", err);
}
});
Try this

Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com

While i click on the login button i get this error :
[19:49:11] [2018-12-25T20:49:57.389Z] #firebase/database:, FIREBASE
FATAL ERROR: Cannot parse Firebase url. Please use https://<YOUR
FIREBASE>.firebaseio.com
- node_modules/#firebase/logger/dist/index.cjs.js:69:32 in
defaultLogHandler
- node_modules/#firebase/logger/dist/index.cjs.js:159:31 in error
- node_modules/#firebase/database/dist/index.cjs.js:333:20 in fatal
- node_modules/#firebase/database/dist/index.cjs.js:1256:14 in
parseRepoInfo
- node_modules/#firebase/database/dist/index.cjs.js:15103:38 in
refFromURL
* src/modules/auth/api.js:24:24 in getUser
* src/modules/auth/api.js:19:32 in <unknown>
- node_modules/#firebase/auth/dist/auth.js:17:105 in <unknown>
- node_modules/#firebase/auth/dist/auth.js:20:199 in Fb
- ... 13 more stack frames from framework internals
I copied and pasted the config stuff directly from Firebase, so it should be correct, but I get this error anyway. What could be causing this? Is there any way the URL I'm copying from my database could be wrong somehow?
As you you can see in the error shown are in my file api.js in
.then((user) => getUser(user, callback))
and in
database.refFromURL('users').child(user.uid).once('value')
So here is my code from api.js is like this :
import { auth, database, provider } from "../../config/firebase";
export function register(data, callback) {
const { email, password } = data;
auth.createUserWithEmailAndPassword(email, password)
.then((user) => callback(true, user, null))
.catch((error) => callback(false, null, error));
}
export function createUser (user, callback) {
database.refFromURL('users').child(user.uid).update({ ...user })
.then(() => callback(true, null, null))
.catch((error) => callback(false, null, {message: error}));
}
export function login(data, callback) {
const { email, password } = data;
auth.signInWithEmailAndPassword(email, password)
.then((user) => getUser(user, callback))
.catch((error) => callback(false, null, error));
}
export function getUser(user, callback) {
database.refFromURL('users').child(user.uid).once('value')
.then(function(snapshot) {
const exists = (snapshot.val() !== null);
if (exists) user = snapshot.val();
const data = { exists, user }
callback(true, data, null);
})
.catch(error => callback(false, null, error));
}
can anyone please help where i missed up
i used
database.ref(`users/`+user.uid).once('value')
instead of
database.refFromURL('users').child(user.uid).once('value')
and it works fine for me now.
Please go through this documentation and update to new modular type or if you want to use old structure then, update to
<script src="https://www.gstatic.com/firebasejs/8.5.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.5.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.5.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.5.0/firebase-storage.js"></script>
update all to version 8.5.0. Will work flawless
The refFromURL method expects a fully qualified URL to the database. So something starting with https://<YOUR
FIREBASE>.firebaseio.com as the error message shows.
You're trying to access a path within the configured database, in which case you should use ref(...) instead:
database.ref('users').child(user.uid).once('value')
I think there are mainly two types of realtime db urls , one ends with ".firebaseio.com" which is for US and other like EU and asia have url which ends with "firebasedatabase.app"
"Please use https://.firebaseio.com", this error comes at line when u call firebase.database(), It can happen that firebase library or module you are using are of old versions which can only make call for db whose url ends with firebaseio.com,
so make sure to update it,
or you can just change the region of your realtime database to US region.

Categories

Resources