Firebase push get key with sdk 9 modular approach - javascript

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);

Related

How to manipulate strings inside array from a fetch response?

I am looking for some assistance with my fetch response from the Online Movie Database API . I am able to succesfully get a response to log in the console, which is what I want. However I am trying to manipulate the response.
I want to pull the most popular shows from the API (API sends 100 titles), and trim it down to 8 titles. I did that using the .splice method. It returns an array of 8 strings representing a title id.
Example: '/title/tt11198330'
Lastly I want to trim each 8 of the strings so it gets rid of the /title/ and all I have left is tt11198330. I am trying to do this inside the .then and when I console.log that forEach that is saved as 'trimmer' it gives me undefined instead of the trimmed result I was intending. But if I console.log the element in the forEach it does show the trimmed strings. Any idea why its undefined, and is there maybe a better way to go about this?
// fetch for most popular shows
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'Z2EvqnO4xwmsh2eY3rMTIV2ivj5hp1QsuGUjsnrYp69UBS4EI5',
'X-RapidAPI-Host': 'online-movie-database.p.rapidapi.com'
}
};
fetch('https://online-movie-database.p.rapidapi.com/title/get-most-popular-tv-shows?currentCountry=US&purchaseCountry=US&homeCountry=US', options)
.then(response => response.json())
.then(response => {
const list = response.splice(0, 8)
let trimmer = list.forEach(element => console.log(element.slice(7, 17)))
console.log(trimmer)
})
.catch(err => console.error(err));
because you are using forEach and it doesn't return data, use map instead.
fetch('https://online-movie-database.p.rapidapi.com/title/get-most-popular-tv-shows?currentCountry=US&purchaseCountry=US&homeCountry=US', options)
.then(response => response.json())
.then(response => {
const list = response.splice(0, 8)
let trimmer = list.map(element => element.slice(7, 17))
console.log(trimmer)
})
.catch(err => console.error(err));

firebase: don't get data from realtime database

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.

Cypress - get value from json response body

I'm using Cypress to do some API testing, but I am struggling to access values in the JSON response body; however I can perform assertions against the body which suggests it's receiving it correctly.
Below I am trying to assign the JSON body (response.body) and then get the value of 'id' out of it:
describe('Creating a board', () => {
it('should create a board', () => {
cy.request({
method : 'POST',
url:`${requestUrl}/boards/`,
qs: {
name : "test-board",
token : token,
key : key
}
}).then((response) => {
expect(response).property('status').to.equal(200)
expect(response.body).property('id').to.not.be.oneOf([null, ""])
const body = (response.body)
boardId = body['id']
})
})
I've done numerous searches and can't find a concrete way to do it. Any help would be appreciated...
I managed to solve this by using a Promise;
Doing some further reading, I found out the then function I am executing is synchronous (I'm new to JS, pls don't hurt me).
I refactored the then function to the following:
.then((response) => {
return new Promise(resolve => {
expect(response).property('status').to.equal(200)
expect(response.body).property('id').to.not.be.oneOf([null, ""])
const respBody = response.body;
boardId = respBody['id']
resolve(boardId)
})
It's probably not entirely correct or best practice, but it will do for my demo
Although not needed anymore as you found a workaround, I've looked into my cypress code. I was able to access properties of response body followingly:
cy.request({
...
}.its('body').then((body) => {
const whatever = body.whatever;
})
I believe it basically works the same as your workaround - waiting to resolve body in a promise.
I was able to do it in the following way:
cy.request(
'POST',
url,
payload()).then((response) => {
expect(response.body).to.have.property('ReturnCode', 'Success')
expect(response.body).to.have.property('ReturnText', 'Success')
expect(response.body).to.have.property('PaymentInstructionId')
paymentID = response.body.PaymentInstructionId
})
paymentID is the variable that is filled with the value that i want from the repply.

Saving data from JSON end point

I am trying to map over the returned json and save the id into profile/profiles. However it does not seem to be mapping over the the data correctly, id: ${ profile.id } this bit needs to be changed? Any help is much appreciated.
Is their a online tool that can help with me this?
API request:
// Grabs company data from the json url
private getProfiles() {
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWVYPpPYivKNWVO8jsTx2eveV3kBg'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response =>
response.data.map(profile => ({
id: `${ profile.id }`
}))
)
.then(profiles => {
this.setState({
profiles
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
}
Json data returned:
{
"localizedLastName": "King",
"id": "fm0B3D6y3I",
"localizedFirstName": "Benn"
}
When I console log the response.data
If the only data returned from your endpoint is the JSON you posted, then you don't have an array to map over.
You have a single object.
I've never used the axios library before, but looking at the source code response.data should be the JSON-parsed responseText from the XHR request:
https://github.com/axios/axios/blob/4f189ec80ce01a0275d87d24463ef12b16715d9b/lib/adapters/xhr.js#L51-L53
https://github.com/axios/axios/blob/4f189ec80ce01a0275d87d24463ef12b16715d9b/lib/defaults.js#L61
And now I see that you have posted response.data and it matches what I'd expect.
With that in mind I'd suggest handling it like this:
// Grabs company data from the json url
private getProfiles() {
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWVYPpPYivKNWVO8jsTx2eveV3kBg'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response => ({
id: profile.id
}))
.then(profiles => {
this.setState({
profiles
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
}
What you're getting back is a single profile though. If you need profiles to be an array you'll need to put the response in an array.
I don't get it, what you are trying to do. In the map you have a callback function, but as I see you wrote there an object. If you are wanting to rewrite the current profile's id then write this:
response.data.map(profile => ({
profile.id = `${ profile.id }`;
}))
But if you want it to make a variable then this:
response.data.map(profile => ({
let id = `${ profile.id }`;
}))

Firebase push promise never resolves

I am trying to save an object from my React Native App. Please look at the below code snippet.
const { currentUser } = firebase.auth();
firebase.database().ref(`/users/${currentUser.uid}/employees`)
.push({ name, phone, shift })
.then(() => {
console.log('Save to Firebase was successful');
})
.catch((error) => {
console.log(error);
});
But in the Firebase console, I don't see anything. I am surprised that the then and catch don't even get called. What am I missing? The console does not show any error.
My Firebase DB Rules:
Here's my Firebase realtime DB view:
Question- I am pushing to /users/${currentUser.uid}/employees path, do I need to manually create 'users' node?
In Firebase push() function genrates a unique key for each new child, and set() or update() functions insert or update data in node.
Try this:
firebase.database().ref(`/users/${currentUser.uid}/employees`)
.push()
.set({ name, phone, shift })
.then(() => {
console.log('Save to Firebase was successful');
})
.catch((error) => {
console.log(error);
});
Or this:
let niceKey = firebase.database().ref(`/users/${currentUser.uid}/employees`).push()
niceKey.set({ name, phone, shift })
.then(() => {
console.log('Save to Firebase was successful');
})
.catch((error) => {
console.log(error);
});
Don't use push to save data to Firebase, instead use set or update. Here's how it works:-
firebase.database().ref(`/users/${currentUser.uid}/employees`).set({
name: name,
phone: phone,
shift : shift
});
For more info visit:- https://firebase.google.com/docs/database/web/read-and-write
Hope it'll help.

Categories

Resources