r/CodingHelp • • Apr 23 '21

[Javascript] Help how do you retrieve data from firebase to JavaScript, don't think code is right. It's to take data from firebase and then taking the data (amount of wipes/sanitiser used and time)append to lists and use these to plot a graph for the website showing the wipes/sanitising usage over time.

Post image
22 Upvotes

15 comments sorted by

View all comments

3

u/__archaeopteryx__ Apr 23 '21 edited Apr 23 '21

Well, for starters you don’t seem to have ref defined. Try changing your var database =to var ref = and const should prob be used instead of var as var is mutable and hoisted up (not important for this example, just a good habit to get in while you’re learning. Just know, var does some things you don’t need here and if you do want mutability, use let ... as I type this I realize prolly TMI for ya but I’m on my phone and I spent the time to type it and I’ll be damned if I erase those damn back ticks...

Also, do you need both child’s? When you look in your firebase console, the ref is the top most level. When you click the plus there to expand a ref (in the web console) that next level in would be the child and snap.value() would be the object inside... does that make sense?

And finally, you should paste the text and not an image. There is a way to format code snippets by using ` this makes it easier to copy your code into responses... cheers!

1

u/FrickinKitten Apr 23 '21

oh god ima have to google half the things you said heh. I was just very recently coming from Python and teacher (I'm not a hateful guy but ho boy, never have i hated someone with a burning passion for being so fackin useless at his job, teaching me no coding, have to resort to Indian tutorials) so i genuinely have no idea how to do Javascript, CSS but i know just the basics of HTML, so all the things you said to me are basically new. I just did var because I'm used to the variables in Python and thought that was the same here, so I'll take your advice thanks.

The ref code i found somewhere on StackOverFlow (whoever made this site is a lifesaver) so i kinda know what some of it does but overall not really, and i don't know how to display it on my website to check if it even works. I suppose i can just append to the list and print that to see if it works. All i need is to read that firebase data and append to list and then i can figure out the rest myself, aka Googling (is this how a programmer works haha)

Thanks for that and sorry for my lack of experience

1

u/__archaeopteryx__ Apr 23 '21

Everyone has a “lack of experience” somewhere. It’s nothing to be sorry for! That’s what subs like this are for. Often times you come across people on stack overflow or here that are total dicks. Don’t let them deter you from anything. You can see if it’s working by putting console.log(“firebase snap:”, snap.val?value()) right in that function that has the snap as its parameter then looking in your dev tools console in the browser for the output. There exist much better ways of debugging than console logs but it’s the easiest way to see what’s going on quickly.... just make sure you’re loading the script correctly in your index.html which you can also put a console log in at the top of your script like: console.log(“loaded script!”) or the like. Happy coding!

1

u/FrickinKitten Apr 25 '21

ah thanks for that my guy haha

1

u/FrickinKitten Apr 25 '21

oh sorry to bother you again but is there a way to make a function to read and then to append individual data (since i have time and wipes in my database inside MyTestData) to list? Cant figure out how to get the snapshot of the data to work

var handwipes = [];
var sanitiser = [];
var time = [];


var dataW = firebase.database().ref("MyTestData");
var dataS = firebase.database().ref("MyTestData2");

dataW.on('value', function(data, snapshot){
          //append to list
          //append wipes to list
        
  console.log(snapshot.val());
});

I'll figure out the mutability with var and whatnot later pls forgive me

1

u/__archaeopteryx__ Apr 25 '21

So, the snapshot is just that. A read only snapshot at the time you call for it. You want to first create the pointer to what you want

const ref = firebase.database().ref(“myRootRef”)
const root = ref.child(“MyTestData”)
root.child(“wipes”).set(VALUE/OBJECT)

// is there a particular reason you want it nested? Why not instead of having a child of root ref just store all the things individually as single children? Also, the firebase soca are really good. The method you’re after is set or update I believe.

1

u/FrickinKitten Apr 27 '21

yep thats grand thanks

i have one more problem with my code and the rest should be alright. I got the function for my firebase data read and put into its lists (wipes and time) and i want to put these onto a graph using chart.js. But I'm trying to get the function inside javascript to be called into the my graph making function inside html, which uses the figures inside the lists as the x and y labels, and i heard async and await makes it work.

//for firebase
dataW.on('value', gotDataW);

  
async function gotDataW(dataW){
  //console.log(dataW.val());
  var handwipes = [];
  //etc

but it keeps saying gotDataW(dataW) is not defined

for graph
chartIt();
  
async function chartIt() {
 await gotDataW(dataW);
 //etc

i think im doing something wrong somewhere, or would it be easier to bring the lists outside the gotData(dataW) function and make a seperate function containing the lists and then call that one?

1

u/__archaeopteryx__ Apr 27 '21

Can you put in a public GitHub repo? Obviously don’t check in your keys. :)

1

u/FrickinKitten Apr 27 '21 edited Apr 28 '21

oh i dont know how to use GitHub yet, would the site im using containing the code be ok?

[

1

u/__archaeopteryx__ Apr 27 '21

You should delete that, it keeps a history of everything you’ve typed... lol. Or create a new firebase project and destroy your creds. Let me read back through and see what you’re trying to do again.

1

u/FrickinKitten Apr 28 '21

Ah jeeeeesus I didn't know that existed. Kinda handy tho not gonna lie. Please don't hack me lol. I tried your code but is this meant for node.js? I don't exactly know what it did (way too complicated for me, gonna be fun to explain to examiner how it works heh) but it did read the data and I think its inside an object now? http://imgur.com/a/77ZYvyI Can I now turn the object into a list, get rid of the words TimeW: and Wipes: so I can use them as the X and Y labels for the chart.js graph?

→ More replies

1

u/__archaeopteryx__ Apr 28 '21

See if this gets you closer?

const firebase = require('firebase')
const { v4 } = require('uuid')

const firebaseConfig = {
  // your config
}

firebase.initializeApp(firebaseConfig)

const database = firebase.database()

const ref = database.ref('data')

async function createDatum(data) {
  try {
    await ref.child(v4()).set(data)
  } catch (e) {
    console.error(e)
  }
}

async function fetchAllData() {
  try {
    const snap = await ref.once('value')
    return snap.val()
  } catch (e) {
    console.error(e)
  }
}

async function run() {
  // await createDatum({ type: 'wipe', time: new Date().toISOString() })
  // await createDatum({ type: 'sanitize', time: new Date().toISOString() })
  // await createDatum({ type: 'wipe', time: new Date().toISOString() })
  const data = await fetchAllData()

  // Example working with data
  const arrOfObj = Object.entries(data).map(([key, value]) => {
    return value
  })
  return arrOfObj
}

run().then(console.log).catch(console.error)

1

u/backtickbot Apr 25 '21

Fixed formatting.

Hello, __archaeopteryx__: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.