These are chat archives for FreeCodeCamp/HelpJavaScript

9th
Feb 2018
FlashHero
@FlashHero
Feb 09 00:39
@sjames1958gm @cmccormack
@cjlynch12 thanks
CamperBot
@camperbot
Feb 09 00:39
flashhero sends brownie points to @sjames1958gm and @cmccormack and @cjlynch12 :sparkles: :thumbsup: :sparkles:
:cookie: 421 | @cjlynch12 |http://www.freecodecamp.org/cjlynch12
:star2: 8952 | @sjames1958gm |http://www.freecodecamp.org/sjames1958gm
:star2: 1312 | @cmccormack |http://www.freecodecamp.org/cmccormack
Zunaid Aslam
@ZunaidAslam
Feb 09 05:16

In the code for seek and destroy


function destroyer(arr) {
  // Remove all the values
  return arr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Why does it return only the part of the value?
-> [1, 2, 3, 1, 2, 3]
Why not?
-> [1, 2, 3, 1, 2, 3], 2, 3

How will I compare them? I was trying to slice them but it's not working?

Claudio Restifo
@Marmiz
Feb 09 05:24

@Zunaid-Aslam have you checked some comparison method for arrays?
for example indexOf?
you can combine it with a filtering method to know if a value is one of the seeker or not.

But there are tons of different approaches... it's better that you start and then we can help you on whatever you've built.

Fabien SHAN
@X140hu4
Feb 09 05:33
@Zunaid-Aslam Because arr is the first argument provided and you define only one argument in the function
@Zunaid-Aslam You can add more argument when calling the function, but you need to access them in the function.
@X140hu4 try return arguments[1];
Ken Haduch
@khaduch
Feb 09 05:58
@Zunaid-Aslam - I don't know if the explanations here answer your question, but what you are to return is an array (most likely not going to be the input array) after you have removed items that are given in the other function arguments. You use the "Arguments object" (they provide a link to the documentation) to find those other function arguments, and then you filter out elements from the array (the first argument) and return an array that has what is remaining.
Zunaid Aslam
@ZunaidAslam
Feb 09 06:36
@Marmiz It's not about starting. I actually have an idea on how to solve it. By issue is shouldn't the value of arr be : 1, 2, 3, 1, 2, 3], 2, 3
Fabien SHAN
@X140hu4
Feb 09 06:38
No because you have 3 arguments when you call the destroyer functions here
Zunaid Aslam
@ZunaidAslam
Feb 09 06:38
@X140hu4 I tried return arr[1] and arr[2] but basically it's using the first array. Rest of the values are not being used.
Shouldn't all the values enter the function as argument
Fabien SHAN
@X140hu4
Feb 09 06:38
No
Markus Kiili
@Masd925
Feb 09 06:38
@Zunaid-Aslam There is only one parameter arr defined in the function, and three arguments are passed. One parameter catches only the first passed argument.
Zunaid Aslam
@ZunaidAslam
Feb 09 06:38
Ok let's say I wanted to return 1, 2, 3, 1, 2, 3], 2, 3, then what do I have to do
Is it like function (arr, a, b)
Markus Kiili
@Masd925
Feb 09 06:39
Use the arguments object that contains all the passed arguments.
Adding parameters doesn't work because the number of arguments in not known.
Zunaid Aslam
@ZunaidAslam
Feb 09 06:40
function destroyer(arr, a, b) {
  // Remove all the values
  return a;
}

destroyer([1, 2, 3, 1, 2, 3], 4, 4);
This worked
I have some Gap in understanding the logic
Markus Kiili
@Masd925
Feb 09 06:40
You can do that when you know the number of passed arguments. Here you don't.
Zunaid Aslam
@ZunaidAslam
Feb 09 06:41
This is why I am asking these question. While Freecodecamp is awesome. But I believe I need to have some supplementary materials.
Aditya
@ezioda004
Feb 09 06:41
@Zunaid-Aslam If you're going to modify the parameters then might as well use spread operator
function destroyer(...arr) {
  // Remove all the values
  return arr;
}

destroyer([1, 2, 3, 1, 2, 3], 4, 4);
Zunaid Aslam
@ZunaidAslam
Feb 09 06:43

@ezioda004 I don't know many concepts. That's why i get stuck at times.

I thought arr basically holds all the values. So I wanted to slice it in half and then compare and eliminate the values that needs to be removed.

But later realised arr only stores = [1, 2, 3, 1, 2, 3]

So, now I will try to change my logic.

I will check into using arguments as objects @Masd925
Aditya
@ezioda004
Feb 09 06:45
@Zunaid-Aslam Thats because as @Masd925 said, in the function you have 1 parameter arr but when invoking you're passing 3 arguments. So JS assigns arr = [1, 2, 3, 1, 2, 3] it doesnt know about the rest passed ie 4, 4
Zunaid Aslam
@ZunaidAslam
Feb 09 06:45
Another thing is, I find https://developer.mozilla.org/en-US/ confusing. I understand many issue but it also raises other issues.
Either my knowledge of English is not good enough to grasp the concept from mozilla.
Or it's not that well explained.
Yeah I understood that after putting more argument and returning their value.
Aditya
@ezioda004
Feb 09 06:46
@Zunaid-Aslam IMO it takes time to get familiar with MDN, took me awhile too but when you get there you'll always use it as reference whenever stuck.
Markus Kiili
@Masd925
Feb 09 06:47
@Zunaid-Aslam There is a special arguments object that you can use inside a function. In this case arguments[0] would be [1,2,3,1,2,3], arguments[1] would be 4 and arguments[2] would be 4. You can loop the passed arguments from the arguments object.
Zunaid Aslam
@ZunaidAslam
Feb 09 06:49
Thanks @Masd925 I am reading about it. And thank you also for the idea.
CamperBot
@camperbot
Feb 09 06:49
zunaid-aslam sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 4689 | @masd925 |http://www.freecodecamp.org/masd925
abraham anak agung
@padunk
Feb 09 10:08
Hi All, what is max heap sort? how to implement it on js? is it better than just sort ?
Markus Kiili
@Masd925
Feb 09 10:17
@padunk The JS standard doesn't say what algorithm Array.prototype.sort must use, so it depends on browser and perhaps on the sorted data too. Most likely algorithms are Quick sort and Merge sort. Heap sort is kind of improved Selection sort.
abraham anak agung
@padunk
Feb 09 10:22
@Masd925 what is Heap sort? I google it, but don't really understand how it works
Markus Kiili
@Masd925
Feb 09 10:26
@padunk I only know what the wikipedia article says about it.
Quantomistro3178
@Quantomistro3178
Feb 09 10:50
Guys, if I have a number and I wanna split up the digits and store them in an array, like a string, how can I do that?
.split() doesnt work
Aditya
@ezioda004
Feb 09 10:53
@Quantomistro3178 Convert the number into string?
let num = 12345;
let str = String(num).split("");
console.log(str); //["1", "2", "3", "4", "5"];
Quantomistro3178
@Quantomistro3178
Feb 09 11:06
@ezioda004 I tried that, but I need to use the number as a NUMBER after, you know what I mean?
@ezioda004 I'll just convert the array values into numbers, that would work right?
@ezioda004 thanks!
CamperBot
@camperbot
Feb 09 11:07
quantomistro3178 sends brownie points to @ezioda004 :sparkles: :thumbsup: :sparkles:
:cookie: 445 | @ezioda004 |http://www.freecodecamp.org/ezioda004
Stephen James
@sjames1958gm
Feb 09 11:07
@Quantomistro3178 Use .map to convert back to numbers
Quantomistro3178
@Quantomistro3178
Feb 09 11:08
one more thing
Stephen James
@sjames1958gm
Feb 09 11:09
@Quantomistro3178
[].map.call(String("123"), (d) => Number(d));
Quantomistro3178
@Quantomistro3178
Feb 09 11:09

function destroyer(arr) {
  // Remove all the values
  var args = [];
  for (var i=1;i<arguments.length; i++) {
    args.push(arguments[i]);
  }
  function filter(a,b,c) {
    for (var i=0; i<args.length;i++) {
      return a !== args[i];
    }
  }
  return arr.filter(filter);
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);
My filter function returns before the loop finishes, how can I avoid that?
Markus Kiili
@Masd925
Feb 09 11:10
@Quantomistro3178 Return false if you find a matching element and true after the loop.
Quantomistro3178
@Quantomistro3178
Feb 09 11:11
@Masd925 But wouldn't the function still end once i return false after finding a matching element?
Markus Kiili
@Masd925
Feb 09 11:12
@Quantomistro3178 Only the callback function returns then and tells filter method to keep/discard the element being iterated.
If you find a matching element, you know the element needs to be discarded.
Quantomistro3178
@Quantomistro3178
Feb 09 11:13
@Masd925 oh
Quantomistro3178
@Quantomistro3178
Feb 09 11:20
@Masd925 How do I do return true/false outside the loop?
Stephen James
@sjames1958gm
Feb 09 11:25
@Quantomistro3178 return true; after the loop closing } of the loop
Simon Cordova
@gbsimon87
Feb 09 12:44
Good morning all.
Afternoon**
Markus Kiili
@Masd925
Feb 09 12:56
@gbsimon87 Yo.
Simon Cordova
@gbsimon87
Feb 09 13:00
What's going on.
First day at my new job, oh my
Markus Kiili
@Masd925
Feb 09 13:04
@gbsimon87 Yeah. Globe theory, reptilians -> Work all day long.
Simon Cordova
@gbsimon87
Feb 09 13:06
Thanks Obama!
lol
Hey I've got a question for you.
Markus Kiili
@Masd925
Feb 09 13:08
@gbsimon87 :ear:
Simon Cordova
@gbsimon87
Feb 09 13:08
I'm working on a e gaming site and need to know how they get the dynamic odds for the available bets.
Any reccos on the best way to go about this?
I've been saying the data come in from the network tab, I just can't seem to console out anything on every AJAX request.
I've been seeing**
Markus Kiili
@Masd925
Feb 09 13:12
@gbsimon87 Hard to say anything with just that information. I also have to leave, so hopefully someone else can help you.
Tom
@moT01
Feb 09 13:21
@gbsimon87 any luck?
Simon Cordova
@gbsimon87
Feb 09 13:23

@Masd925 no worries, cheers

@moT01 not so much just yet no

I've noticed the request headers and where the bets are coming in from, but I need to be able to inject some JS into that page and also generate bets with dynamic odds.
I'm thinking I may need access to their API
Stephen James
@sjames1958gm
Feb 09 13:25
@gbsimon87 New job? Congrats if so.
Simon Cordova
@gbsimon87
Feb 09 13:26
@sjames1958gm
Thanks a lot :)
I actually started with this company about a month ago but have been working in the south of England, I'm officially at my new office starting today. Second programming job though!
CamperBot
@camperbot
Feb 09 13:26
gbsimon87 sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8955 | @sjames1958gm |http://www.freecodecamp.org/sjames1958gm
Sweet Coding :)
@SweetCodingInc
Feb 09 13:26
@gbsimon87 Congrats :)
Simon Cordova
@gbsimon87
Feb 09 13:27
I've certainly got my feet in the field now but can't stop, there's lots to learn
@SweetCodingInc thanks a lot
CamperBot
@camperbot
Feb 09 13:27
gbsimon87 sends brownie points to @sweetcodinginc :sparkles: :thumbsup: :sparkles:
:cookie: 262 | @sweetcodinginc |http://www.freecodecamp.org/sweetcodinginc
Sweet Coding :)
@SweetCodingInc
Feb 09 13:27
@gbsimon87 No worries. You'll be fine
Stephen James
@sjames1958gm
Feb 09 13:29
@gbsimon87 :+1:
@gbsimon87 Where are you working now? If not South of England
Sweet Coding :)
@SweetCodingInc
Feb 09 13:30
@sjames1958gm Are you from the UK, too?
Stephen James
@sjames1958gm
Feb 09 13:30
No I am in Texas
Sweet Coding :)
@SweetCodingInc
Feb 09 13:30
Wrong guess based on Chelsea logo :laughing:
Stephen James
@sjames1958gm
Feb 09 13:31
Yeah, not a bad guess - I am one of the few (but growing) soccer fans in the US
Simon Cordova
@gbsimon87
Feb 09 13:31
I'm Canadian but yes I'm in London atm
MLS fan as well @sjames1958gm ?
Sweet Coding :)
@SweetCodingInc
Feb 09 13:31
@sjames1958gm Arsenal fan here :wave:
More specifically Man U hater :laughing:
Stephen James
@sjames1958gm
Feb 09 13:31
@gbsimon87 Not so much. Quality is so much higher over in the premiere league
@SweetCodingInc lol
@SweetCodingInc Gooner :)
Sweet Coding :)
@SweetCodingInc
Feb 09 13:32
KTBFFH
@gbsimon87 Why did you travel that far? There is already a London in Canada :laughing:
Simon Cordova
@gbsimon87
Feb 09 13:33

All my friends here are Gooners actually

@sjames1958gm I was asking because Toronto FC won their first MLS cup last season

Do any of you guys have experience with Knockout JS?
Stephen James
@sjames1958gm
Feb 09 13:34
@gbsimon87 Still waiting for Dallas FC to make it further in the playoffs
@gbsimon87 I have only heard the name
Simon Cordova
@gbsimon87
Feb 09 13:36
May be quicker than the Mavs making a statement, although they've got an amazing player now in Dennsi Smith Jr.
Don't know if you're into basketball
Stephen James
@sjames1958gm
Feb 09 13:46
@gbsimon87 Mostly soccer and the Cowboys until they eff it up
Simon Cordova
@gbsimon87
Feb 09 13:47
Didn't know they had a team since Aikman and Smith lol
Just playing...
Stephen James
@sjames1958gm
Feb 09 14:12
@gbsimon87 :)
Simon Cordova
@gbsimon87
Feb 09 14:37
Signing off for a bit
Cheers to all! :)
Tiago Correia
@tiagocorreiaalmeida
Feb 09 15:31
@AdelMahjoub by any luck around?
Tiago Correia
@tiagocorreiaalmeida
Feb 09 15:40
anyone around here uses bulma?
Dany Din
@danydin
Feb 09 15:54
how to convert <script>async src="https://....." </script>into .js file?
Jason Luboff
@JLuboff
Feb 09 16:10
@tiagocorreiaalmeida Yes, I do
@tiagocorreiaalmeida I used Bulma for my voting, nightlife, and stock apps
Tiago Correia
@tiagocorreiaalmeida
Feb 09 16:14
uh cool, and hey :D, so im having some issues somehow their is-6 and others column class once they are one line full they dont stack to below they are going on line out of screen
image.png
probably missing some important class
Jason Luboff
@JLuboff
Feb 09 16:15
@tiagocorreiaalmeida As far as I know, Bulma does not stack like Bootstrap, as I ran into the same issue. I had to programmically account for such scenarios
Tiago Correia
@tiagocorreiaalmeida
Feb 09 16:15
hum that doesnt makes alot of sense :\
but probably you are right
Jason Luboff
@JLuboff
Feb 09 16:16
I'm not saying it makes sense lol
Tiago Correia
@tiagocorreiaalmeida
Feb 09 16:17
yeyyy
found it out
is-multiline
:D
yup worked perfect
Jason Luboff
@JLuboff
Feb 09 16:18
Hmmm.. I had used is-multiline but it gave me trouble (or I used it somewhere else, maybe in a form?) I dunno
Well just ignore me then :)
Tiago Correia
@tiagocorreiaalmeida
Feb 09 16:18
no worries took me a while to figure out how it works so and thanks tough
Jason Luboff
@JLuboff
Feb 09 16:22
:+1:
Tiago Correia
@tiagocorreiaalmeida
Feb 09 16:24
what you working on?
Jason Luboff
@JLuboff
Feb 09 16:26
Working on deploying my first C# production app! Just finished modifying the production database so now have to go into my app change the database connection string and test it
Tiago Correia
@tiagocorreiaalmeida
Feb 09 16:29
nice :)
Jason Luboff
@JLuboff
Feb 09 16:31
Yup, then have to work on installing node and mongo onto Ubuntu to get my second production project done (conference room sign that technically is in place already, but I've added the ability to add more than just the current days events, the ability to edit, etc and got rid of PHP that didn't work half the time)
Markus Kiili
@Masd925
Feb 09 16:33
@JLuboff :imp:
Jason Luboff
@JLuboff
Feb 09 16:34
@Masd925 You have a bot that detects any time someone says PHP? :P
Markus Kiili
@Masd925
Feb 09 16:34
@JLuboff Yes, you woke me up.
Jason Luboff
@JLuboff
Feb 09 16:34
@Masd925 Sounds like a personal issue :joy:
Tiago Correia
@tiagocorreiaalmeida
Feb 09 16:38
fcc comunity is like an anti php comunity :D
Jason Luboff
@JLuboff
Feb 09 16:38
PHP is awful
I made a change in my php.ini file. Forgot a ' I think. Didn't know I had an issue until over a month later becuase my form submissions still worked (which used php to redirect) but my outgoing mail wasn't working
Markus Kiili
@Masd925
Feb 09 16:40
@JLuboff I always start learning a new language by reading what is wrong with it. Doing that for php has taken 4 years. For reasonable languages it takes 4 minutes.
Jason Luboff
@JLuboff
Feb 09 16:40
:joy:
Sweet Coding :)
@SweetCodingInc
Feb 09 16:41
Php.. My old <3
You all can imagine how terrible the relationship went
Jason Luboff
@JLuboff
Feb 09 16:42
@SweetCodingInc PHP took half your things and ran off with Java?
Sweet Coding :)
@SweetCodingInc
Feb 09 16:43
not only that, my kids (projects) died, 17 of my best friends got "lucky"
Jason Luboff
@JLuboff
Feb 09 16:45
Depressing
Sweet Coding :)
@SweetCodingInc
Feb 09 16:45
Yeah </3
Glad I found JS <3
who is rich
Jason Luboff
@JLuboff
Feb 09 16:47
:D
Markus Kiili
@Masd925
Feb 09 16:52
@JLuboff I managed to make a working version of the bus departure app (some features missing). Found out that geolocation doesn't work with http.
Jason Luboff
@JLuboff
Feb 09 16:53
@Masd925 browser geolocation? Used to work in Firefox, but I think within the last few versions they stopped supporting it
Nazar
@IsaakNazar
Feb 09 16:53
hi guys
how to multiply very long numbers in JS ?
10 ^ 1 000 000 ?
Aditya
@ezioda004
Feb 09 16:59
@IsaakNazar I think you'd have to use some library like BigInteger.js since in js the maximum safe integer value is 9007199254740991.
Nazar
@IsaakNazar
Feb 09 17:00
@ezioda004 how to make it possible without any libraries?
Aditya
@ezioda004
Feb 09 17:02
@IsaakNazar I'm not sure if thats possible without a library..
Nazar
@IsaakNazar
Feb 09 17:06
@ezioda004 the purpose of the task is to find the last digit of the result number
example
4 ^ 2 = 16 => last digit is 6
5 ^ 3 = 125 => 5
10 ^ 10000000000 => 0
and so on
both numbers are strings
lastDigit(str1, str2)
lastDigit("4", "2") => 6
Aditya
@ezioda004
Feb 09 17:09
@IsaakNazar I think this is more of a Math problem than programming, I remember there was a logic for finding the last digit, I'll look for it
Adel
@AdelMahjoub
Feb 09 17:12
@tiagocorreiaalmeida for bulma the .containerclass should always be a direct child of any layout class, .hero, .section, .level inside a .level-item`. When used as the top most wrapper the page won't be responsive as you expected. the `.columns` usage is the same as in bootstrap, should be nested in a `.container`, vertically center columns using `.is-vcentered`, horizontally center columns using `is-centered`. When you don't know how many columns you'll use, you add the `.is-multiline`, control the gap between columns using `ìs-variable` + the gap size `is-1` up to 8. If you want the columns to apply on small screens you add the.is-mobile` class
Tiago Correia
@tiagocorreiaalmeida
Feb 09 17:16
@AdelMahjoub finding it a bit confusing to get used but seems a nice framework
and thanks tough
Adel
@AdelMahjoub
Feb 09 17:17
@tiagocorreiaalmeida the only big difference is the .container compared to bootstrap 3, should never be the top most parent
@tiagocorreiaalmeida .section is the equivalent of bs3 .container
Aditya
@ezioda004
Feb 09 17:18

@IsaakNazar Ok so apparently theres a pattern that starts forming for the digits like this

0,0,0,0   
1,1,1,1   
2,4,8,6   
3,9,7,1   
4,6,4,6   
5,5,5,5   
6,6,6,6   
7,9,3,1   
8,4,2,6   
9,1,9,1

so say you have 2^18 means it will follow 2,4,8,6pattern every 4 power so 18%4 would give 2 remainder therefore the last digit would be 4from the pattern.

Jason Luboff
@JLuboff
Feb 09 17:18
@tiagocorreiaalmeida There's some nice free themes for bulma too btw
Adel
@AdelMahjoub
Feb 09 17:18
@tiagocorreiaalmeida There's some nice free themes for bulma too btw :+1:
Tiago Correia
@tiagocorreiaalmeida
Feb 09 17:19
image.png
yeha allready making use of parts of it making personal changes
but ofcourse using allready made up things
but yeah and the design looks alot better, a bit tired of the bs one
Nazar
@IsaakNazar
Feb 09 17:23
@ezioda004 just for example how to find 123 ^ 87163 ?
Adel
@AdelMahjoub
Feb 09 17:24
@tiagocorreiaalmeida if you want the content to not stretch on wide screens >1400px, which will look a bit too 'wide' and big, as if the content was zoomed add a media query on the .container to have the max desired width
Nazar
@IsaakNazar
Feb 09 17:27
@ezioda004 thx man, got it :)
CamperBot
@camperbot
Feb 09 17:27
isaaknazar sends brownie points to @ezioda004 :sparkles: :thumbsup: :sparkles:
:cookie: 447 | @ezioda004 |http://www.freecodecamp.org/ezioda004
Aditya
@ezioda004
Feb 09 17:27
@IsaakNazar The last digit in 123 is 3 and the remainder from 87163 % 4 is 3 so the pattern of 3 at unit place is 3,9,7,1 and the 3rd no in that pattern is 7 so answer should be 7.
@IsaakNazar :thumbsup: awesome :)
Tiago Correia
@tiagocorreiaalmeida
Feb 09 17:28
thanks @AdelMahjoub brownies all the way :D
CamperBot
@camperbot
Feb 09 17:28
tiagocorreiaalmeida sends brownie points to @adelmahjoub :sparkles: :thumbsup: :sparkles:
Nazar
@IsaakNazar
Feb 09 17:28
@ezioda004 perfect :+1: appreciate, thx
CamperBot
@camperbot
Feb 09 17:28
:cookie: 656 | @adelmahjoub |http://www.freecodecamp.org/adelmahjoub
isaaknazar sends brownie points to @ezioda004 :sparkles: :thumbsup: :sparkles:
api offline
Dany Din
@danydin
Feb 09 17:30
can someone help me with google anlaytics code?
Tiago Correia
@tiagocorreiaalmeida
Feb 09 17:30
@danydin sure
you jhust have to place it where they point it and nothing to worry about more
Dany Din
@danydin
Feb 09 17:31
yes but i see many people make it a function and i wonder what it does different :p
something like this
!function(e,a,t,n,g,c,o){e.GoogleAnalyticsObject=g,e.ga=e.ga||function(){(e.ga.q=e.ga.q||[]).push(arguments)},e.ga.l=1*new Date,c=a.createElement(t),o=a.getElementsByTagName(t)[0],c.async=1,c.src="https://www.google-analytics.com/analytics.js",o.parentNode.insertBefore(c,o)}(window,document,"script",0,"ga"),ga("create","UA-102261065-1","auto"),ga("send","pageview")
Markus Kiili
@Masd925
Feb 09 17:33
@JLuboff Yeah. Time to learn how to serve https from apache.
Jason Luboff
@JLuboff
Feb 09 17:51
@Masd925 Get yourself a certificate
Markus Kiili
@Masd925
Feb 09 17:54
@JLuboff Yeah.
Brad
@bradtaniguchi
Feb 09 18:17
@danydin I think they make it a function that they can call for special actions. As I know you can track almost anything with google analytics. But this is just a guess from my knowledge of google analytics
Naw I take it back, the tracking for actions looks totally different
@danydin From me just looking at the function itself, it looks like the normal ga code, except for the !in front, which I'm not sure what its for. The code itself is a self invoking function, so the function is called after being declared with the (window, document, "script", 0, "ga")arguments.
jusgoose
@gusd773
Feb 09 18:21
anybody have links to help me prepopulate a tweet with my random quote setup the way it is? I understand that for my random quote button it needs the getjson to change my $(".message").html so I tried doing the same for my tweet out button using $(this)("href" * but it's not working :(

 $(function() {
             $('#getQuote').click(function() {
                 $.ajaxSetup({
                     cache: false
                 });
                 $.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
                     $(".message").html(a[0].content + "<p>— " + a[0].title + "</p>")
                 });

             });
             $('#tweetQuote').click(function() {
                         $.ajaxSetup({
                             cache: false
                         });
                         $.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {

                             $(this).attr("href", 'https://twitter.com/intent/tweet/?text=' + a[0].content + "<p>— " + a[0].title + "</p>");

                         });
                     });
                  });
Nazar
@IsaakNazar
Feb 09 18:25
@ezioda004 need your help
Matej Bošnjak
@mbosnjak01
Feb 09 18:27
@gusd773 when you click on #getQuote button to show random quote, that quote isn't the same as #tweetQuote because tweetQuote gets another random quote, which means it's not the same you got in the first place -> since it's doing another (or, second) getJSON request
jusgoose
@gusd773
Feb 09 18:28
@mbosnjak01 dangit u rite
Matej Bošnjak
@mbosnjak01
Feb 09 18:28
What I would try here
is to wrap the quote you get inside the variable and pass that variable to tweet
Nazar
@IsaakNazar
Feb 09 18:28
@ezioda004 lastDigit("3715290469715693021198967285016729344580685479654510946723", "68819615221552997273737174557165657483427362207517952651")
browser cant find reminder for the second parameter
Matej Bošnjak
@mbosnjak01
Feb 09 18:29
and each time you get new quote, that variable would store that current quote text/author or whatever you need, so you can pass it further. Can be done with array as well
Sweet Coding :)
@SweetCodingInc
Feb 09 18:30
@IsaakNazar what aer you trying to do? That number seems too huge to process
Matej Bošnjak
@mbosnjak01
Feb 09 18:30
@gusd773 so .. that getJSON in tweetQuote shouldn't be there at all.
Nazar
@IsaakNazar
Feb 09 18:31
@SweetCodingInc trying to find reminder from the second argument
secondArgument % 4
Matej Bošnjak
@mbosnjak01
Feb 09 18:32
I didn't make tweet button but I'll try to implement it on my code now
got nothing better to do atm XD
Nazar
@IsaakNazar
Feb 09 18:32
browser gave me 0
Sweet Coding :)
@SweetCodingInc
Feb 09 18:33
@IsaakNazar can you show your code?
Nazar
@IsaakNazar
Feb 09 18:33
@SweetCodingInc
var lastDigit = function(str1, str2){
  var last = str1[str1.length-1];
  var reminder = +str2 % 4;
  var x;
  var dig2 = [2, 2, 4, 8, 6],
  dig3 = [3, 3, 9, 7, 1],
  dig4 = [4, 4, 6, 4, 6],
  dig7 = [7, 7, 9, 3, 1],
  dig8 = [8, 8, 4, 2, 6],
  dig9 = [9, 9, 1, 9, 1];

  switch (last) {
    case '0':  x = 0;
      break;
    case '1':  x = 1;
      break;
    case '2':  x = dig2[reminder];
      break;
    case '3':  x = dig3[reminder];
      break;
    case '4':  x = dig4[reminder];
      break;
    case '5':  x = 5;
      break;
    case '6':  x = 6;
      break;
    case '7':  x = dig7[reminder];
      break;
    case '8':  x = dig8[reminder];
      break;
    case '9':  x = dig9[reminder];
      break;
    default: x = 'none of them';

  }
  return x;
}
console.log(lastDigit("3715290469715693021198967285016729344580685479654510946723", "68819615221552997273737174557165657483427362207517952651"));
jusgoose
@gusd773
Feb 09 18:34
@mbosnjak01 OK 2 questions: 1) so you mean wrap the quote inside "A" variable right? (not sure cuz you said "THE" variable lol) 2) I am not sure where to place my second click event (maybe inside the first click event funtion???) since I would only be able to access the variables inside that getJson request ?
Sweet Coding :)
@SweetCodingInc
Feb 09 18:35
@IsaakNazar its 0 becuase number is buffer overflow... I'd suggest you do % on say last 4 5 digits. It would give you the same result mathematically
Nazar
@IsaakNazar
Feb 09 18:35
@SweetCodingInc function should return last digit of str1 ^ str2
Sweet Coding :)
@SweetCodingInc
Feb 09 18:36
like +(str2.slice(-4)%4)
Matej Bošnjak
@mbosnjak01
Feb 09 18:36
@gusd773 if you make variable like this inside click function: var A = someValue -> var A is global and can be used in other functions...if you make it like this: let A = someValue -> variable can be used only within that function. Buy you can define variable outside of click event, on the beggining of the script like var A; and then do A = quoteText inside your click event.
Sweet Coding :)
@SweetCodingInc
Feb 09 18:37
@IsaakNazar does ^ mean raised to the power here?
Nazar
@IsaakNazar
Feb 09 18:37
@SweetCodingInc yes
Sweet Coding :)
@SweetCodingInc
Feb 09 18:37
geez
Nazar
@IsaakNazar
Feb 09 18:39
@SweetCodingInc as you said, if I do % to the last 4-5 digit , does it give me correct result?
Sweet Coding :)
@SweetCodingInc
Feb 09 18:39
it should
since it's remainder opeerator
and since you're doing %4, you will only get one of 0,1,2,3 as output
even last 2 digits would also do
Nazar
@IsaakNazar
Feb 09 18:41
@SweetCodingInc I think you are right, I'll check the code out once again using your suggestion
jusgoose
@gusd773
Feb 09 18:42
@mbosnjak01 I get that but it doesn't make sense without calling on getJSON
like this
 $(function(){  
     $('#getQuote').click(function(){
       var A = "someVal";
       var B = "diffVal";
        $.ajaxSetup({cache:false});
or this
  var A = "someVal";
       var B = "diffVal";

  $(function(){  
     $('#getQuote').click(function(){
        $.ajaxSetup({cache:false});
Christopher McCormack
@cmccormack
Feb 09 18:46
@gusd773 use the latter, store the quote you get back from the api call using getJSON in one of your global variables (A or B in this case) then you can use that variable whenever you want
Matej Bošnjak
@mbosnjak01
Feb 09 18:46
^
Nazar
@IsaakNazar
Feb 09 18:46
@SweetCodingInc brilliant, thx :+1:
CamperBot
@camperbot
Feb 09 18:46
isaaknazar sends brownie points to @sweetcodinginc :sparkles: :thumbsup: :sparkles:
:cookie: 268 | @sweetcodinginc |http://www.freecodecamp.org/sweetcodinginc
Sweet Coding :)
@SweetCodingInc
Feb 09 18:47
@IsaakNazar worked?
Christopher McCormack
@cmccormack
Feb 09 18:47
bad practice to use caps for variables that aren't "classes" or components though, FYI
Nazar
@IsaakNazar
Feb 09 18:47
@SweetCodingInc yess, with your help
Sweet Coding :)
@SweetCodingInc
Feb 09 18:47
@IsaakNazar :+1:
jusgoose
@gusd773
Feb 09 18:47
@cmccormack but wouldn't that only alter var A & B once they click the getQuote button?
Christopher McCormack
@cmccormack
Feb 09 18:48
@gusd773 isn't that what you want?
Matej Bošnjak
@mbosnjak01
Feb 09 18:48
I just did that and it works.
jusgoose
@gusd773
Feb 09 18:49
@cmccormack no I need it to tweet out the same random quote pressing tweetQuote as it would as if I pressed getQuote
Christopher McCormack
@cmccormack
Feb 09 18:49
@gusd773 if you're worried about populating the variables on page load as well, you can duplicate the code within our IIFE but outside the click handler
jusgoose
@gusd773
Feb 09 18:49
@mbosnjak01 i'm gonna fix mine rn
Christopher McCormack
@cmccormack
Feb 09 18:50
@gusd773 right, if your getQuote is storing the current quote in variable A, then tweetQuote should be able to use variable A to tweet the quote
Matej Bošnjak
@mbosnjak01
Feb 09 18:50
but you can't get the same random quote by doing 2 json calls
Christopher McCormack
@cmccormack
Feb 09 18:50
A would be global so all functions would have access to it
Matej Bošnjak
@mbosnjak01
Feb 09 18:50
so you need to get it on your getquote, store it in variable and then tweet it
let me just finish tweet button and i'll show you my code if you want
Christopher McCormack
@cmccormack
Feb 09 18:50
@mbosnjak01 @gusd773 ah yeah I didn't see his code until now, @gusd773 you shouldn't be doing any api calls to the quote api in your tweetquote
you should already have a quote, either from when the page loads or when the user clicks getQuote
jusgoose
@gusd773
Feb 09 18:52
@mbosnjak01 @mbosnjak01 so I am kinda confused, I thought the code after
  $(function(){  
     $('#getQuote').click(function(){
        $.ajaxSetup({cache:false});
          $.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(quote) {
is supposed to only work once that getQuote button is pressed? So why would clicking the tweetQuote change A & B? That's what I'm misunderstanding
Don't get me wrong I'm SO glad that works lol I just wanna know why
Christopher McCormack
@cmccormack
Feb 09 18:53
@gusd773 no, use getQuote to change A and B
ACCESS A and B from tweetQuote but don't modify
jusgoose
@gusd773
Feb 09 18:56


       var A = "someVal";
       var B = "someVal";

  $(function(){  
     $('#getQuote').click(function(){
        $.ajaxSetup({cache:false});
          $.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(quote) {
      var A= quote[0].content;
      var B= quote[0].title;
  $(".message").html( A + "<p>— " + B + "</p>")
});
                                   });
        $('#tweetQuote').click(function(){


    $(this).attr("href",'https://twitter.com/intent/tweet/?text='+ A + "<p>— " + B + "</p>");

  });
});
@cmccormack @mbosnjak01 that's my understanding rn
Brad
@bradtaniguchi
Feb 09 18:57
@gusd773 LGTM, except what happens if they click the tweatQuote before they use get quote? It would show someVal and someVal right?
Matej Bošnjak
@mbosnjak01
Feb 09 18:58
when you make var A and B on the top, don't write var inside function. call them without var .. just A = something; B = something;
jusgoose
@gusd773
Feb 09 18:58
@bradtaniguchi that's what I was asking
Matej Bošnjak
@mbosnjak01
Feb 09 18:58
adding var again will just recreate variable
Christopher McCormack
@cmccormack
Feb 09 18:58
@gusd773 don't declare your var again
Matej Bošnjak
@mbosnjak01
Feb 09 18:58
question
Brad
@bradtaniguchi
Feb 09 18:58
Op yup, didn't see that haha
Matej Bošnjak
@mbosnjak01
Feb 09 18:58
does tweet button works on localhost?
cause it just won't fire the link
:|
jusgoose
@gusd773
Feb 09 18:59
@mbosnjak01 it was working earlier
Brad
@bradtaniguchi
Feb 09 18:59
It should if your getJSON link is correct, unless your getting an error
Matej Bošnjak
@mbosnjak01
Feb 09 18:59
i just get error 404 XD
json link is good
jusgoose
@gusd773
Feb 09 18:59
@bradtaniguchi I mean it works to get my random quotes
Matej Bošnjak
@mbosnjak01
Feb 09 18:59
tweet link however won't fire
Christopher McCormack
@cmccormack
Feb 09 19:00
don't you need the widget?
jusgoose
@gusd773
Feb 09 19:00
@mbosnjak01 I'll grab some lighter fluid
Matej Bošnjak
@mbosnjak01
Feb 09 19:01
dang. what widget? XD
i guess i do
Jason Luboff
@JLuboff
Feb 09 19:02
@cmccormack twitter widget? I don't think I used one for my project.
Christopher McCormack
@cmccormack
Feb 09 19:02
@JLuboff I can't remember if it's required or not, probably not
probably not for a web intent anyhow
Matej Bošnjak
@mbosnjak01
Feb 09 19:02
class="twitter-share-button"
i had to add this in ma anchor
to make it work
thanks @cmccormack :D
CamperBot
@camperbot
Feb 09 19:02
mbosnjak01 sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:star2: 1313 | @cmccormack |http://www.freecodecamp.org/cmccormack
Christopher McCormack
@cmccormack
Feb 09 19:03
Did I help with that? haha
glad you got it working!
Jason Luboff
@JLuboff
Feb 09 19:04
@mbosnjak01 I think thats what I did
jusgoose
@gusd773
Feb 09 19:04
@mbosnjak01 I JUST read that lol
Christopher McCormack
@cmccormack
Feb 09 19:05
Hah apparently I made an example pen I forgot about https://codepen.io/cmccormack/pen/LjvmKZ
maybe this will help
Mine doesn't work without the widget though, things may have changed
jusgoose
@gusd773
Feb 09 19:07
@mbosnjak01 you added it to your anchor button in place of class="btn btn-default"? Mine still isn't firing
Matej Bošnjak
@mbosnjak01
Feb 09 19:07
not in place, just added as another class
jusgoose
@gusd773
Feb 09 19:08
@mbosnjak01 ok yea I tried that still a fireless caveman
Christopher McCormack
@cmccormack
Feb 09 19:12
@mbosnjak01 are you doing it in a pen? can you share it? DM if you don't want spoilers for others :)
Jason Luboff
@JLuboff
Feb 09 19:14
@cmccormack Too bad there isn't a spoiler tag in gitter
Christopher McCormack
@cmccormack
Feb 09 19:14
Maybe there is and we just don't know because people keep using it
Matej Bošnjak
@mbosnjak01
Feb 09 19:15
i can share if needed
Christopher McCormack
@cmccormack
Feb 09 19:15
I don't need I just want to see how you did it without the widget
I can add to my example pen
Matej Bošnjak
@mbosnjak01
Feb 09 19:16
ignore index file for the most part, it's old xD
Christopher McCormack
@cmccormack
Feb 09 19:17
why php?
oh ok
haha
oh you do have the widget
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
@JLuboff did you check if you use it?
Matej Bošnjak
@mbosnjak01
Feb 09 19:20
when I tweet, it just wants to tweet my localhost link
do i have to be logged in twitter or? DX
Christopher McCormack
@cmccormack
Feb 09 19:21
not sure what you mean - are you getting a popup first?
Matej Bošnjak
@mbosnjak01
Feb 09 19:21
Christopher McCormack
@cmccormack
Feb 09 19:21
But no you should not have to be logged in
haha
Matej Bošnjak
@mbosnjak01
Feb 09 19:22
I guess something is blocking the script
i'll try to rearange my index file
no luck. gg twitter
jusgoose
@gusd773
Feb 09 19:24
@mbosnjak01 @cmccormack @JLuboff sheesh this must be a good challenge lol
sorry for the madness
Christopher McCormack
@cmccormack
Feb 09 19:26
@mbosnjak01 is it using the url var from the #new onclick? that's weird
Matej Bošnjak
@mbosnjak01
Feb 09 19:27
yep
Christopher McCormack
@cmccormack
Feb 09 19:28
you may need to use this.url
not sure
Matej Bošnjak
@mbosnjak01
Feb 09 19:29
tried that as well
this makes me cry
xD
Christopher McCormack
@cmccormack
Feb 09 19:31
oh maybe you need to declare it so it's locally scoped
try adding var url=... within the function
Brad
@bradtaniguchi
Feb 09 19:33
There's always window.url, thats bound to be something (global vars are evil)
Matej Bošnjak
@mbosnjak01
Feb 09 19:33
nothing works, i just get to tweet my localhost link :'D
Brad
@bradtaniguchi
Feb 09 19:34
How come the index is a php file? yyyyy
And it looks like your loading jquery twice?
Matej Bošnjak
@mbosnjak01
Feb 09 19:34
as i mention earlier, it's old, i didn't change to html on github
it's html on local
i removed that as well
Brad
@bradtaniguchi
Feb 09 19:35
Alright
Jason Luboff
@JLuboff
Feb 09 19:37
@cmccormack No, I don't have that. https://codepen.io/jluboff/pen/GqyXdg (shits broken...ignore that)
Matej Bošnjak
@mbosnjak01
Feb 09 19:40
ok
got it
my bad
was using anchor for no reason :|
Jason Luboff
@JLuboff
Feb 09 19:41
It's only taken over 3.5 hours.... but finally have my first C# production app deployed. Wooo!
Matej Bošnjak
@mbosnjak01
Feb 09 19:42
Christopher McCormack
@cmccormack
Feb 09 19:42
Ah ok - so @JLuboff yours is just a link, but if you use the widgets you get a popup instead
Matej Bošnjak
@mbosnjak01
Feb 09 19:43
i replaced anchor with a button tag
gg
Jason Luboff
@JLuboff
Feb 09 19:43
@cmccormack Maybe when I actually go back and fix it (to use my API none the less :joy: ) I'll add that
Christopher McCormack
@cmccormack
Feb 09 19:43
@JLuboff haha yeah I noticed that
Got to eat your own dogfood!
Jason Luboff
@JLuboff
Feb 09 19:45
I let my dog eat my dogfood :P
Matej Bošnjak
@mbosnjak01
Feb 09 19:46
@gusd773 https://github.com/mbosnjak01/Random-quote-machine if you want to check it out.
@cmccormack it works without widget as well now
Christopher McCormack
@cmccormack
Feb 09 19:48
@mbosnjak01 widget isn't required, it just does some work for you like make it pop up in its own window and look nice
I was testing on codepen and forgot you need target="_blank" when testing without the widget that's why I wasn't sure
Glad you got it working @mbosnjak01 !
Matej Bošnjak
@mbosnjak01
Feb 09 19:49
window.open ("https://twitter.com/intent/tweet?text="+quoteText + " - " + quoteAuthor, '_blank'); made the trick
with button tag ... damn anchors, will not use them again :|
Christopher McCormack
@cmccormack
Feb 09 19:52
anchors work perfectly fine
I modified my example pen to exclude the widgets and use an anchor: https://codepen.io/cmccormack/pen/LjvmKZ
jusgoose
@gusd773
Feb 09 19:54
@mbosnjak01 so that last '_blank' was it?
Matej Bošnjak
@mbosnjak01
Feb 09 19:54
no
I removed anchor tag and widget completely, replaced it with a button, and then added a function to that button inside js file.
jusgoose
@gusd773
Feb 09 19:55
@mbosnjak01 I am looking at the script rn sorry
Matej Bošnjak
@mbosnjak01
Feb 09 19:56
For some reason anchor was interfering with my script, to be more precise, it's default href attribute. No clue what was goind there or why, since I tried several options. I'm glad this works, and it stays sealed :D
@gusd773 all good XD
Christopher McCormack
@cmccormack
Feb 09 19:56
@mbosnjak01 I think you had something else, but we never saw your most recent code so hard to tell.
Jason Luboff
@JLuboff
Feb 09 19:57
Curious...any one know of another resource similar to github that is less expensive for private repos?
Christopher McCormack
@cmccormack
Feb 09 19:58
bitbucket
Matej Bošnjak
@mbosnjak01
Feb 09 19:58
@cmccormack Yeah. I should have saved all my failures to inspect the code more :( Oh well, I guess I'll do that next time :)
Christopher McCormack
@cmccormack
Feb 09 19:58
@mbosnjak01 that's why version control exists!
commit more often :)
Matej Bošnjak
@mbosnjak01
Feb 09 19:59
i'm lazy
:(
Christopher McCormack
@cmccormack
Feb 09 19:59
yeah I feel ya
Matej Bošnjak
@mbosnjak01
Feb 09 19:59
and yes, github private repos are expensive
Christopher McCormack
@cmccormack
Feb 09 19:59
I'll code for a couple hours, do a git status, see 12 items, and lazily do git commit -am "Updated" haha
not like anyone ever looks at it anyhow
Jason Luboff
@JLuboff
Feb 09 20:00
@cmccormack Thanks. Looks like it'd be free for private repos for me
CamperBot
@camperbot
Feb 09 20:00
jluboff sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:star2: 1314 | @cmccormack |http://www.freecodecamp.org/cmccormack
Jason Luboff
@JLuboff
Feb 09 20:00
Exactly what I want lol
Matej Bošnjak
@mbosnjak01
Feb 09 20:00
what's better it when somebody updates a file with like 30k lines of code with a comment "bugs fixed"
Jason Luboff
@JLuboff
Feb 09 20:00
I haven't used git at all for my C# app but want to push it to an online repo so I can access it else where if needed
Christopher McCormack
@cmccormack
Feb 09 20:01
I may use it too, I have a personal site I want to keep backed up in a repo but don't really want it public
Sometimes I wonder what the point of the commit message is when you have a diff anyhow
I guess maybe a marker in time if you need to go way back
Jason Luboff
@JLuboff
Feb 09 20:02
Ya I can't imagine my company would be too happy about having a a public repo with the in house code that was build lol
Matej Bošnjak
@mbosnjak01
Feb 09 20:02
I might just buy Synergy with 1T SSD and make my own servers
Jason Luboff
@JLuboff
Feb 09 20:03
Anywho...lunch time..be back in a while
Christopher McCormack
@cmccormack
Feb 09 20:03
@JLuboff see ya
@mbosnjak01 I've thought about doing that with my RPi server just never got around to it. Would be pretty easy as I already have OpenVPN setup so I can push to it anywhere with an Internet connection
Matej Bošnjak
@mbosnjak01
Feb 09 20:04
And you can connect to your synergy from anywhere (even mobile app) and do stuff there
I guess I'll skip buying crap and invest some money in that
in a few months
Christopher McCormack
@cmccormack
Feb 09 20:07
eh get a cheap 160GB SSD and an RPi, you can do pretty much the same thing
Matej Bošnjak
@mbosnjak01
Feb 09 20:07
i'll get at least 500GB :D
Christopher McCormack
@cmccormack
Feb 09 20:08
it's all about scale
You can get a 240 for like $75USD right now and that's plenty for "cloud storage" purposes
jusgoose
@gusd773
Feb 09 20:21
@mbosnjak01 yea man that's looking like a foreign language lines 1:12
I'm not sure how that's supposed to relate to my getJSON api call
Christopher McCormack
@cmccormack
Feb 09 20:23
@JLuboff so I just setup my bitbucket account, created a private repo, added my SSH key, cloned the new repo, pushed my project up, and it was all just as easy as github
Matej Bošnjak
@mbosnjak01
Feb 09 20:24
@gusd773 jquery getJSON is shorter for jquery ajax call which I have in my code
it's all the same in the end
@gusd773 what part of my code is unclear? :D
jusgoose
@gusd773
Feb 09 20:29

so your 1:12 === my 1:12


       var A = "someVal";
       var B = "diffVal";

  $(function(){  
     $('#getQuote').click(function(){
        $.ajaxSetup({cache:false});
          $.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(quote) {
      A= quote[0].content;
      B= quote[0].title;
  $(".message").html( A + "<p>— " + B + "</p>")

});

@mbosnjak01
Matej Bošnjak
@mbosnjak01
Feb 09 20:30
Yes. It does same thing tho.
not sure what you got $ajaxSetup for
jusgoose
@gusd773
Feb 09 20:31
@mbosnjak01 makes sure I don't return the same value everytime it's clicked
Matej Bošnjak
@mbosnjak01
Feb 09 20:32
hmm..
i stil lthink it doesn't need to be there at all, i'd delete it
because
you call random quote, so even if you get by any chance same quote again on the second click .. well, it's called random for a reason :P
but if it works for you, leave it there :)
Christopher McCormack
@cmccormack
Feb 09 20:35
@gusd773 a little trick you can do is to append something like + '&time=' + Date.now() to your url, it will force it to call the server instead of using the cached version
jusgoose
@gusd773
Feb 09 20:37
@mbosnjak01 yea you're right lol but I feel like randomness is super impt in this realm, also my button still wont fire even
after changing the anchor tag to a button tag
sorry I forgot I was human and had to eat
Matej Bošnjak
@mbosnjak01
Feb 09 20:37
lel
i totally forgot to take some dinner
but i'm not hungry .. weird
Keggatron
@Keggatron
Feb 09 20:38
Hey guys, I tried writing a few days ago with a problem I was having but something came up and I couldn't get back to some people. Anyway I've got a React app that for some reason I'm unable to share my props from state with another function in the component. I'm getting a cannot read props of undefined when I submit. Here's the code:
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { barcodeSearch } from '../actions';

class ProductNew extends Component {
  renderProductField(field) {
    const { meta: { touched, error} } = field
    const className = `form-group ${touched && error ? 'has-danger' : ''}`
    console.log(this.props.product);

    return (
      <div className={className}>
        <label>{field.label}</label>
        <input 
          className="form-control"
          type="text"
          value={field.value}
          {...field.input}
        />
        <div className="text-help">
          {touched ? error : ''} 
        </div>
      </div>  


    );
  }

  onSubmit(values) {
    console.log(values);
  }

  render() {
    const { handleSubmit } = this.props;


    return (
      // <div>{console.log(this.props.product)}</div>
      <div>

        <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
          <Field
            label="Name of Product"
            name="name"
            value={this.props.product.name}
            component={this.renderProductField}
          />
          <Field
            label="Brand"
            name="brand"
            component={this.renderProductField}
          />
          <Field
            label="Description"
            name="description"
            component={this.renderProductField}
          />
          <Field
            label="Quantity"
            name="quantity"
            component={this.renderProductField}
          />
          <Field
            label="Price"
            name="price"
            component={this.renderProductField}
          />
          <Field
            label="Category"
            name="category"
            component={this.renderProductField}
          />
          <Field
            label="UPC Code"
            name="upc"
            component={this.renderProductField}
          />
          <Field
            label="Images"
            name="images"
            component={this.renderProductField}
          />

          <button type="submit" className="btn btn-primary"> Submit </button>
          <Link to="/" className="btn btn-danger"> Cancel </Link>
        </form>
      </div>
    )
  }
}

function validate(values) {
  const errors =  {}

  if (!values.name) {
    errors.name = "Enter a name for the product!"
  } 
  if(!values.brand) {
    errors.brand = "Enter a brand for the product!";
  }
  if(!values.description) {
    errors.description = "Enter a description!";
  }
  if(!values.quantity) {
    errors.quantity = "Enter a quantity!";
  }
  if(!values.price) {
    errors.price = "Enter a price!";
  }
  if(!values.category) {
    errors.category = "Enter a category!";
  }
  if(!values.upc) {
    errors.upc = "Enter a UPC!";
  }

  return errors;
}

function mapStateToProps({ newProduct }, ownProps) {
  return { product: newProduct[0][0] };
}

export default reduxForm({
  validate,
  form: 'ProductNewForm'
})(
  connect(mapStateToProps, { barcodeSearch })(ProductNew)
);
Christopher McCormack
@cmccormack
Feb 09 20:39
@gusd773 you don't need the callback= part of your url
Keggatron
@Keggatron
Feb 09 20:39
when I console.log this from the render function though I can see the product that's coming back
jusgoose
@gusd773
Feb 09 20:41

@cmccormack bet but my tweet button still won't work

@mbosnjak01 eat some bytes

Christopher McCormack
@cmccormack
Feb 09 20:42
@gusd773 not sure why you mention your tweet button, did you ask something about it/
jusgoose
@gusd773
Feb 09 20:43
@cmccormack yea I thought that's what this madness was
Christopher McCormack
@cmccormack
Feb 09 20:47
@Keggatron you sure the issue isn't in your handleSubmit function you passed down in props?
@Keggatron it's odd to me you're passing your child componenets onsubmit up to the parent to handle
Keggatron
@Keggatron
Feb 09 20:50
@cmccormack I'm relatively new to React/Redux so I based a lot of this off of an app from one of the courses I used. Not sure if this is the correct thing to do.
Christopher McCormack
@cmccormack
Feb 09 20:50
I would normally invoke the parents handleSubmit from the child's locally bound handleSubmit function if I wanted to add additional logic to it
@Keggatron I see. Unfortunately I haven't dug deep into Redux so I could be leading you astray but if you're able to use this.props in one place in your class I believe you should be able to use it anywhere, so maybe look at the parent's handleSubmit. You should have a stack trace right?
Keggatron
@Keggatron
Feb 09 20:53
I haven't used a stack trace before
Christopher McCormack
@cmccormack
Feb 09 20:53
@Keggatron it should just be how you see the error in your developer console
Looks something like this (found right here in Gitter's dev console )
Unhandled rejection Error: Not Found
    at r (https://cdn02.gitter.im/_s/708c5ff/js/vendor.js:9:21498)
    at Object.error (https://cdn02.gitter.im/_s/708c5ff/js/vendor.js:9:23126)
    at l (https://cdn02.gitter.im/_s/708c5ff/js/vendor.js:3:14505)
AbrisM
@AbrisM
Feb 09 20:54
Glitter has a dev editor? lol
Christopher McCormack
@cmccormack
Feb 09 20:55
well it's the output from Gitter in the Chrome dev console
You word it better :p
AbrisM
@AbrisM
Feb 09 20:55
Ah, cus I just use F12 to bring up the dev tools
Christopher McCormack
@cmccormack
Feb 09 20:56
yes that's what I'm talking about
AbrisM
@AbrisM
Feb 09 20:56
Yea, I notice sometimes it is different between firefox and chrome
Like Chrome will have src folders to look at, firefox lacks that
Christopher McCormack
@cmccormack
Feb 09 20:56
I usually just right click and Inspect or Inspect Element as I'm too lazy
Keggatron
@Keggatron
Feb 09 20:56
this is what I'm getting in the Chrome console:
Uncaught TypeError: Cannot read property '0' of undefined
    at Function.mapStateToProps [as mapToProps] (product-new.js:123)
    at mapToPropsProxy (wrapMapToProps.js:43)
    at Function.detectFactoryAndVerify (wrapMapToProps.js:52)
    at mapToPropsProxy (wrapMapToProps.js:43)
    at handleFirstCall (selectorFactory.js:26)
    at pureFinalPropsSelector (selectorFactory.js:74)
    at Object.runComponentSelector [as run] (connectAdvanced.js:26)
    at Connect.initSelector (connectAdvanced.js:178)
    at new Connect (connectAdvanced.js:119)
    at constructClassInstance (react-dom.development.js:6355)
    at updateClassComponent (react-dom.development.js:7839)
    at beginWork (react-dom.development.js:8225)
    at performUnitOfWork (react-dom.development.js:10224)
    at workLoop (react-dom.development.js:10288)
    at HTMLUnknownElement.callCallback (react-dom.development.js:542)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:581)
    at invokeGuardedCallback (react-dom.development.js:438)
    at renderRoot (react-dom.development.js:10366)
    at performWorkOnRoot (react-dom.development.js:11014)
    at performWork (react-dom.development.js:10967)
    at requestWork (react-dom.development.js:10878)
    at scheduleWorkImpl (react-dom.development.js:10732)
    at scheduleWork (react-dom.development.js:10689)
    at scheduleTopLevelUpdate (react-dom.development.js:11193)
    at Object.updateContainer (react-dom.development.js:11231)
    at react-dom.development.js:15226
    at Object.unbatchedUpdates (react-dom.development.js:11102)
    at renderSubtreeIntoContainer (react-dom.development.js:15225)
    at Object.render (react-dom.development.js:15290)
    at Object../src/index.js (index.js:13)
    at __webpack_require__ (bootstrap 6c8c817afce6da8248c5:678)
    at fn (bootstrap 6c8c817afce6da8248c5:88)
    at Object.0 (reducer_products.js:11)
    at __webpack_require__ (bootstrap 6c8c817afce6da8248c5:678)
    at ./node_modules/ansi-regex/index.js.module.exports (bootstrap 6c8c817afce6da8248c5:724)
    at bootstrap 6c8c817afce6da8248c5:724
mapStateToProps @ product-new.js:123
mapToPropsProxy @ wrapMapToProps.js:43
detectFactoryAndVerify @ wrapMapToProps.js:52
mapToPropsProxy @ wrapMapToProps.js:43
handleFirstCall @ selectorFactory.js:26
pureFinalPropsSelector @ selectorFactory.js:74
runComponentSelector @ connectAdvanced.js:26
initSelector @ connectAdvanced.js:178
Connect(ProductNew) @ connectAdvanced.js:119
constructClassInstance @ react-dom.development.js:6355
updateClassComponent @ react-dom.development.js:7839
beginWork @ react-dom.development.js:8225
performUnitOfWork @ react-dom.development.js:10224
workLoop @ react-dom.development.js:10288
callCallback @ react-dom.development.js:542
invokeGuardedCallbackDev @ react-dom.development.js:581
invokeGuardedCallback @ react-dom.development.js:438
renderRoot @ react-dom.development.js:10366
performWorkOnRoot @ react-dom.development.js:11014
performWork @ react-dom.development.js:10967
requestWork @ react-dom.development.js:10878
scheduleWorkImpl @ react-dom.development.js:10732
scheduleWork @ react-dom.development.js:10689
scheduleTopLevelUpdate @ react-dom.development.js:11193
updateContainer @ react-dom.development.js:11231
(anonymous) @ react-dom.development.js:15226
unbatchedUpdates @ react-dom.development.js:11102
renderSubtreeIntoContainer @ react-dom.development.js:15225
render @ react-dom.development.js:15290
./src/index.js @ index.js:13
__webpack_require__ @ bootstrap 6c8c817afce6da8248c5:678
fn @ bootstrap 6c8c817afce6da8248c5:88
0 @ reducer_products.js:11
__webpack_require__ @ bootstrap 6c8c817afce6da8248c5:678
./node_modules/ansi-regex/index.js.module.exports @ bootstrap 6c8c817afce6da8248c5:724
(anonymous) @ bootstrap 6c8c817afce6da8248c5:724
index.js:2177 The above error occurred in the <Connect(ProductNew)> component:
    in Connect(ProductNew) (created by Form(Connect(ProductNew)))
    in Form(Connect(ProductNew)) (created by Connect(Form(Connect(ProductNew))))
    in Connect(Form(Connect(
Christopher McCormack
@cmccormack
Feb 09 20:57
@Keggatron don't need the whole thing! top few will do
AbrisM
@AbrisM
Feb 09 20:57
Hahaha I only see two error-msgs on glitter's platform
Christopher McCormack
@cmccormack
Feb 09 20:57
@Keggatron the bottom few lines there may be more useful, along with the first couple lines
Conor Murphy
@cmurphy580
Feb 09 20:58
how do you take a date.now() and convert it to ISO Date "2015-03-25" (The International Standard) format? I looked at mozilla and webschools, but neither one say how to get the current month. I can get the current day and year though.
Keggatron
@Keggatron
Feb 09 20:58
index.js:2177 The above error occurred in the <Connect(ProductNew)> component:
    in Connect(ProductNew) (created by Form(Connect(ProductNew)))
    in Form(Connect(ProductNew)) (created by Connect(Form(Connect(ProductNew))))
    in Connect(Form(Connect(ProductNew))) (created by ReduxForm)
    in ReduxForm (created by Route)
    in Route (at App.js:18)
    in Switch (at App.js:16)
    in div (at App.js:15)
    in Router (created by BrowserRouter)
    in BrowserRouter (at App.js:14)
    in div (at App.js:13)
    in App (at index.js:15)
    in Provider (at index.js:14)
Conor Murphy
@cmurphy580
Feb 09 20:59
 let today = new Date(),
     year = today.getFullYear(),
     month = today.getUTCMonth() < 10 ? `0${today.getMonth()}` : '',
     day = today.getDate() < 10 ? `0${today.getDate()}` : '',
     date = `${year}-${month}-${day}`;

 console.log(date);
logs : 2018-9-1
wouldn't that get me 2
Christopher McCormack
@cmccormack
Feb 09 21:00
wait that's wrong one sec
it's february
so it should be 2
> var date = new Date()
> date
2018-02-09T21:00:19.383Z
> date.getMonth()
1
> date.getMonth() + 1
2
Conor Murphy
@cmurphy580
Feb 09 21:01
@cmccormack my bad thats right. Why do you add the 1 though? Shouldn't it return the correct month?
Christopher McCormack
@cmccormack
Feb 09 21:01
0 indexed
yeah it's dumb
Conor Murphy
@cmurphy580
Feb 09 21:02
@cmccormack got it! thank you for the help!
CamperBot
@camperbot
Feb 09 21:02
cmurphy580 sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:star2: 1315 | @cmccormack |http://www.freecodecamp.org/cmccormack
Christopher McCormack
@cmccormack
Feb 09 21:02
np
Jason Luboff
@JLuboff
Feb 09 21:20
@cmccormack :+1: I'll get it setup
Christopher McCormack
@cmccormack
Feb 09 21:21
@JLuboff I bet you will...
Dovydas Stirpeika
@Giveback007
Feb 09 21:31
@cmccormack it's not dumb!!! :D
it's good for when you have an array of month names
Christopher McCormack
@cmccormack
Feb 09 21:31
@Giveback007 The date thing?
@Giveback007 and Hi
Dovydas Stirpeika
@Giveback007
Feb 09 21:31
hey :)
['Jan' ...
or
['January'...
Christopher McCormack
@cmccormack
Feb 09 21:32
@Giveback007 I know why they did it but subtracting one was probably an option as well
Dovydas Stirpeika
@Giveback007
Feb 09 21:33
yeah, true true
especialy since the days are not indexed
Christopher McCormack
@cmccormack
Feb 09 21:33
I guess 0 index is more common so they went that route
Jason Luboff
@JLuboff
Feb 09 21:33
@cmccormack Hey man..I've already created an account!
Dovydas Stirpeika
@Giveback007
Feb 09 21:33
and days of week also 0-6
Christopher McCormack
@cmccormack
Feb 09 21:33
I think day of the week is 0 indexed
dang you beat me to it haha
Dovydas Stirpeika
@Giveback007
Feb 09 21:34
youp
Jason Luboff
@JLuboff
Feb 09 21:34
If I'm working with dates... I love me some momentjs
Dovydas Stirpeika
@Giveback007
Feb 09 21:34
lame
do it by hand or not at all :D
Christopher McCormack
@cmccormack
Feb 09 21:34
oh man by hand is the worst!
Jason Luboff
@JLuboff
Feb 09 21:35
Do with moment and never look back :)
Christopher McCormack
@cmccormack
Feb 09 21:35
I'd much rather use some kind of formatting
Dovydas Stirpeika
@Giveback007
Feb 09 21:35
don't even code it just write it down
Christopher McCormack
@cmccormack
Feb 09 21:35
haha
@Giveback007 how's the job?
Dovydas Stirpeika
@Giveback007
Feb 09 21:35
good
I am working from home today
I feel like I'm killing it
in a good way that is
Christopher McCormack
@cmccormack
Feb 09 21:37
That's awesome
Jason Luboff
@JLuboff
Feb 09 21:37
I wanna work from home :( but then again... I'd probably get no work done
Christopher McCormack
@cmccormack
Feb 09 21:37
I'm more and more wishing I did something like this full time, especially during work hours
Dovydas Stirpeika
@Giveback007
Feb 09 21:38
I am solving puzzles all day
coding puzzles (which is my favorite kind)
Jason Luboff
@JLuboff
Feb 09 21:38
@cmccormack more and more programming?
Christopher McCormack
@cmccormack
Feb 09 21:40
The field I'm in is heavily reliant on vendor equipment with buggy code and proprietary everything. It can be very frustrating and a chore to have to learn a whole new platform every few months because we decided on a different vendor. Coding is so much more pure and the ecosystem vibrant and tons of people have asked the same questions as myself
Jason Luboff
@JLuboff
Feb 09 21:41
Ah, ya I feel you on that. On a different scale I deal with it for new computers. We don't buy computers in batches, so I can never make an image so I have to build up each one from scratch :( I've gotten quick at it but still
Christopher McCormack
@cmccormack
Feb 09 21:43
@Giveback007 what puzzles? Bug fixes?
Dovydas Stirpeika
@Giveback007
Feb 09 21:43
@cmccormack nah, I'm writing code all day every day
lots of asynchronous calls and data manipulation
I'm getting really good at it
Christopher McCormack
@cmccormack
Feb 09 21:44
@Giveback007 Node?
Dovydas Stirpeika
@Giveback007
Feb 09 21:45
Angular
enterprise software for real estate tax service
Jason Luboff
@JLuboff
Feb 09 21:45
@cmccormack where does ssh-keygen live on windows?
Christopher McCormack
@cmccormack
Feb 09 21:45
@JLuboff it doesn't
use git bash
Jason Luboff
@JLuboff
Feb 09 21:46
got it
Christopher McCormack
@cmccormack
Feb 09 21:46
git bash will store it in your C:\Users\[username]\.ssh\ dir
Jason Luboff
@JLuboff
Feb 09 21:47
It's defaulting to my private network location but I can switch it
Christopher McCormack
@cmccormack
Feb 09 21:47
if you're using WSM than you may want to copy it to your ~/.ssh/ directory as well
Jason Luboff
@JLuboff
Feb 09 21:47
WSM?
Christopher McCormack
@cmccormack
Feb 09 21:47
Sorry WSL
I use WSL along with Hyper Terminal for a pretty Linux-like experience, pretty nice
Jason Luboff
@JLuboff
Feb 09 21:48
Oh... not using that
Did you use a passphrase?
Christopher McCormack
@cmccormack
Feb 09 21:49
Mingw will use your normal C:\Users\[username] path as ~ so if you're using VS code or mingw as your terminal you should be good
I don't
key should be enough
but you can
I started moving to SSH with PKI for everything, sure does make the experience better once setup
Jason Luboff
@JLuboff
Feb 09 21:49
saving key failed..ugh
let me switch directories first
Christopher McCormack
@cmccormack
Feb 09 21:50
it should save it to your home directory, that's weird
it may have a path option
Jason Luboff
@JLuboff
Feb 09 21:50
I think my environment is set my GPO to be my private network drive
Christopher McCormack
@cmccormack
Feb 09 21:52
I need to go read up more on how that script works, It's always just worked for me
Jason Luboff
@JLuboff
Feb 09 21:52
Got it. Had to create the hidden ssh folder first
I'm guessing a permissions issue through git bash.. Dunno. But that worked
Christopher McCormack
@cmccormack
Feb 09 21:55
@JLuboff I made a guide for using ZSH on Hyper Terminal with WSL if you're interested. https://github.com/cmccormack/dotfiles/blob/master/ZSH_on_Win_10.md
@JLuboff did you try # sudo ssh-keygen? :)
Jason Luboff
@JLuboff
Feb 09 21:58
I got the key created. Added it, but getting denied (haven't gotten the email?)
Christopher McCormack
@cmccormack
Feb 09 22:03
added the public key on https://bitbucket.org/account/user/jluboff/ssh-keys/? (guessing that's your name)
where are you getting denied, when cloning the repo?
Jason Luboff
@JLuboff
Feb 09 22:03
Ah...I added it to the repo itself. Let me try that location
Christopher McCormack
@cmccormack
Feb 09 22:04
I almost did that too, it's not that intuitive. It said something about read-only access though

Ah I guess this is the point of the Access Keys:

Access keys can be used to allow a build server to authenticate with Bitbucket Cloud to check out and test your code.

Lean Junio
@leanjunio
Feb 09 22:05
Hey guys, is this how you create a promise from inside a function?
exports.initialize = function() {
    // TODO: Read contents of "./data/employees.json"
    fs.readFile('data/employees.json', 'utf-8', (err, data) => {
        employees = JSON.parse(data);

        var employeePromise = new Promise((resolve, reject) => {
            if (employees) {
                resolve(employees);
            } else {
                var reason = new Error("unable to read file");
                reject(reason);
            }
        });
    });

    fs.readFile('data/departments.json', 'utf-8', (err, data) => {
        departments = JSON.parse(data);

        var departmentsPromise = new Promise((resolve, reject) => {
            if (departments) {
                resolve(departments);
            } else {
                var reason = new Error("unable to read file");
                reject(reason);
            }
        });
    });

    // TODO: Assign contents to employees array
    // TODO: then - repeat for "./data/departments.json"
    // TODO: use resolve to communicate back to server
    // TODO: Do error handling
};
Jason Luboff
@JLuboff
Feb 09 22:07
@cmccormack Man... it's all jacked now hahahaa
Christopher McCormack
@cmccormack
Feb 09 22:09
@JLuboff what happened?
@leanjunio are you running into an issue with your implementation?
@leanjunio looks like your promise should probably be wrapped around the readFile
Dovydas Stirpeika
@Giveback007
Feb 09 22:13
@leanjunio your function should return the given promise
Lean Junio
@leanjunio
Feb 09 22:14

Something like this?

exports.initialize = function() {
    return new Promise((resolve, reject) => {

        // Read data
        fs.readFile('data/employees.json', 'utf-8', (err, data) => {
            employees = JSON.parse(data);
        });

        // Read Data
        fs.readFile('data/departments.json', 'utf-8', (err, data) => {
            departments = JSON.parse(data);
        });

        resolve("Success");
    });
};

```

Dovydas Stirpeika
@Giveback007
Feb 09 22:15
yes this will allow you to do
exports.initialize().then((stuff) => 'do something with "stuff" ')
.then() will only execute when your async stuff is done
Jason Luboff
@JLuboff
Feb 09 22:16
@cmccormack I had tried running ssh -T git@bitbucket.org prior to placing the key in the proper location now I get a Permission Denied(publickey) :-\
Christopher McCormack
@cmccormack
Feb 09 22:17
why are you running that?
Dovydas Stirpeika
@Giveback007
Feb 09 22:17
resolve(data)
Jason Luboff
@JLuboff
Feb 09 22:17
@cmccormack Thats what the instructions say to do lol but I'm just going to create a new set of keys
Christopher McCormack
@cmccormack
Feb 09 22:18
where?
Dovydas Stirpeika
@Giveback007
Feb 09 22:18
if you want to run it in the .then((data) => ... )
Christopher McCormack
@cmccormack
Feb 09 22:18
@JLuboff oh you can just literally copy the key and paste it in the GUI
that's all I do, cat ~/.ssh/id_rsa.pub
you probably can't SSH until it has the key :)
That, or you actually pushed a key up before you ran the keygen and didn't need to do anything else
Jason Luboff
@JLuboff
Feb 09 22:20
Christopher McCormack
@cmccormack
Feb 09 22:21
@JLuboff ohh
it's possible it's not using the key in your home directory that you created
Jason Luboff
@JLuboff
Feb 09 22:22
Hmmm.. ya might be looking at my network drive location?
Lean Junio
@leanjunio
Feb 09 22:24
Do you guys know why i can't access the data in employees and departments in the other functions after this?
var employees = new Array();
var departments = new Array();

exports.initialize = function() {
    return new Promise((resolve, reject) => {

        // Read data
        fs.readFile('data/employees.json', 'utf-8', (err, data) => {
            employees = JSON.parse(data);
        });

        // Read Data
        fs.readFile('data/departments.json', 'utf-8', (err, data) => {
            departments = JSON.parse(data);
        });

        resolve("Success");
        reject("unable to read file");
    });
};
Dovydas Stirpeika
@Giveback007
Feb 09 22:24
@leanjunio
exports.initializeFile = (jsonFile) =>
        fs.readFile(`data/${jsonFile}.json`, 'utf-8', (err, data) => doStuffWIthData(data) )

function doStuffWIthData(data) {
  let parsedData = JSON.parse(data)
 // here i use the parsedData 
}
Jason Luboff
@JLuboff
Feb 09 22:25
@cmccormack Yup. It was looking at my network location where I have a key already. Used that key and we're all good now
Dovydas Stirpeika
@Giveback007
Feb 09 22:25
because if you are handling the data before it is assigned a value it will be undefined
Jason Luboff
@JLuboff
Feb 09 22:25
It's the ones I used for github I'm pretty sure
Christopher McCormack
@cmccormack
Feb 09 22:25
@JLuboff may just want to add both for good measure
Jason Luboff
@JLuboff
Feb 09 22:27
@cmccormack GOT IT! Alright got me a private repo lol
Can use this for my next project too... sweet!
Christopher McCormack
@cmccormack
Feb 09 22:28
@JLuboff I'm glad you asked the question because I remember vaguely something I read said it only did free unlimited private Mercurial repos but maybe that was wrong or old info
And I wasn't about to go and learn something slightly different!
Jason Luboff
@JLuboff
Feb 09 22:29
Well it claims its private.. I'm going to DM you the link to make sure you cant access it
Christopher McCormack
@cmccormack
Feb 09 22:29
just test in incognito
Jason Luboff
@JLuboff
Feb 09 22:29
Where's the fun in that?
Christopher McCormack
@cmccormack
Feb 09 22:31
haha
Dovydas Stirpeika
@Giveback007
Feb 09 22:32
@leanjunio why are you using a promise anyways?
looks like you could just execute that data within the call back
Christopher McCormack
@cmccormack
Feb 09 22:37
@Giveback007 Maybe because of // TODO: use resolve to communicate back to server but I have no idea what it's asking for
Jason Luboff
@JLuboff
Feb 09 22:37
Alright...time for NVM install than Mongo install on Linux...wish me luck. I took a snapshot just in case I royally fuck shit up :joy:
Christopher McCormack
@cmccormack
Feb 09 22:37
but the callback could do that as well
@JLuboff gl, don't break anything!
I gotta run myself, later all
Jason Luboff
@JLuboff
Feb 09 22:38
See ya
Dovydas Stirpeika
@Giveback007
Feb 09 22:40
@JLuboff :wave:
@cmccormack :wave:
Jason Luboff
@JLuboff
Feb 09 22:42
@Giveback007 I'm still here, maybe less attentive for a while though
Dovydas Stirpeika
@Giveback007
Feb 09 22:42
ahh well then I take back my wave
Jason Luboff
@JLuboff
Feb 09 22:43
:D
Lean Junio
@leanjunio
Feb 09 22:49
@Giveback007 assignments :/
Dovydas Stirpeika
@Giveback007
Feb 09 22:49
@leanjunio so are you required to use a promise?
Lean Junio
@leanjunio
Feb 09 22:49
@Giveback007 yep
I'm not sure I'm seeing the difference from my sntax
var employees = new Array();
var departments = new Array();

exports.initialize = function() {

    // Read data
    fs.readFile('data/employees.json', 'utf-8', (err, data) => {
        employees = JSON.parse(data);
    });

    // Read Data
    fs.readFile('data/departments.json', 'utf-8', (err, data) => {
        departments = JSON.parse(data);
    });

    return new Promise((resolve, reject) => {
        resolve("Success");
        reject("unable to read file");
    });
};
The global arrays are empty when I'm attempting to access them from diffrent functions
Dovydas Stirpeika
@Giveback007
Feb 09 22:52
exports.initializeFile = (jsonFile) =>
  new Promise((res, rej) => {
    fs.readFile(`data/${jsonFile}.json`, 'utf-8', (err, data) => res(data) )
  })

function setEmployees(data) {
  employees = JSON.parse(data)
 // here i run more code for the employees data
}

exports.initializeFile('employees')
  .then(data => setEmployees(data))
@leanjunio
can you tell what I am doing different
try to read it first before you say no (if that is your initial response)
Lean Junio
@leanjunio
Feb 09 22:56
This one yes?
exports.initializeFile('employees')
  .then(data => setEmployees(data))
Dovydas Stirpeika
@Giveback007
Feb 09 22:57
read my first 4 lines and tell me what is different there
Lean Junio
@leanjunio
Feb 09 22:58
Mine is employees = JSON.parse(data); while yours is res(data)
Dovydas Stirpeika
@Giveback007
Feb 09 22:58
do you understand why I did it like this?
Lean Junio
@leanjunio
Feb 09 22:59
unfortunately i don't
Dovydas Stirpeika
@Giveback007
Feb 09 22:59
well because you don't want resolve() or res() to run until your computer is done reading the data
otherwise your promise will just run resolve("Success") right away
the data reading is dome asynchronously while all other code is runing synchronously
Lean Junio
@leanjunio
Feb 09 23:14
Okay, this is what I have now...
exports.initialize = function() {
    return new Promise((resolve, reject) => {
        fs.readFile('data/employees.json', 'utf-8', (err, data) => {
            resolve(data)
            reject("Cannot read data from employees");
        });
        fs.readFile('data/departments.json', 'utf-8', (err, data) => {
            resolve(data);
            reject("Cannot read data from departments");
        });
    })

    function setEmployees(data) {
        employees = JSON.parse(data);
    }

    function setDepartments(data) {
        reject("unable to read file");
        departments = JSON.parse(data);
    }
};
Dovydas Stirpeika
@Giveback007
Feb 09 23:14
getting closer
Lean Junio
@leanjunio
Feb 09 23:14
app.get('/employees', (req, res) => {
    dataService.getAllEmployees().then((data) => {
        res.json(data);
    })
});

// This route will return a JSON formatted string containing all the employees whose isManager property is set to true.
app.get('/managers', (req, res) => {

});

app.get('/departments', (req, res) => {
    dataService.initialize()
        .then((data) => res.send(data));
})

app.get('*', (req, res) => {
    res.send("Page Not Found");
    res.status(404);
})

dataService.initialize()
    .then((data) => {
        app.listen(port, () => console.log(`Listening on port ${port}`));
    })
    .catch(() => {
        console.log("There was an error initializing");
    })
Dovydas Stirpeika
@Giveback007
Feb 09 23:14
but only one of them will run
Lean Junio
@leanjunio
Feb 09 23:14
I'm trying to call the promise so that when I get to /employees, it will return the data to the view
Dovydas Stirpeika
@Giveback007
Feb 09 23:16
you have to understand what a promise is
Lean Junio
@leanjunio
Feb 09 23:16
hmm right...it's a future value that will be returned when I call it...?
Dovydas Stirpeika
@Giveback007
Feb 09 23:16
it is an object that will return what ever data is within the resolve() function
resolve(data)
you are "resolving" the data
"then" once the data is resolved .then
.then() you want to do something with that data
.then((data) => i will do stuff with data
.then((data) => handlerFunction(data))
the benefit of a promise is that it will only run ".then()" when the "resolve()" function runs
Lean Junio
@leanjunio
Feb 09 23:20
Right...so in this case, I shouldn't even be reading the json file within the promise...
Is that correct?
Dovydas Stirpeika
@Giveback007
Feb 09 23:20
you can
but its easier to do everything within the handeler function
Lean Junio
@leanjunio
Feb 09 23:21
however, it will only return one of them correct?
Dovydas Stirpeika
@Giveback007
Feb 09 23:21
yes once the "resolve()" function runs the promise is done
Lean Junio
@leanjunio
Feb 09 23:22
at this moment, I'm just trying to create initialize so that within it, it's readFile - ing employees.json and departments.json to the global variable arrays.
Is a promise even needed for something like that?
Dovydas Stirpeika
@Giveback007
Feb 09 23:23
if I made a promise to you that at a later time I will give you $5 and I fulfilled that promise "resolve($5)" then I no longer owe you the promise
Lean Junio
@leanjunio
Feb 09 23:23
right
Dovydas Stirpeika
@Giveback007
Feb 09 23:24
in the same way once the promise is resolved ".then((money) => console.log(money))" // $5
since the fs.readFile is asynchronous you can just do this
exports.initializeFile = (fileName) =>
        fs.readFile(`data/${fileName}.json`, 'utf-8', (err, data) => doStuffWIthData(data) )

function doStuffWIthData(data) {
  let parsedData = JSON.parse(data)
 // here i use the parsedData 
}
Lean Junio
@leanjunio
Feb 09 23:31
Is it possible to get employees and departments within the same initializeFIle function?
Dovydas Stirpeika
@Giveback007
Feb 09 23:33
even better
exports.initializeFile = (fileName, callBack) =>
        fs.readFile(`data/${fileName}.json`, 'utf-8', (err, data) => callBack(data) )

function setDataA(data) {
  let parsedData = JSON.parse(data)
 // here i use the parsedData 
}

function setDataB(data) {
  let parsedData = JSON.parse(data)
 // here i use the parsedData 
}

exports.initializeFile('fileA', setDataA)
exports.initializeFile('fileB', setDataB)
@leanjunio
is this making sense
Lean Junio
@leanjunio
Feb 09 23:35
it is, however, in this assignment, we are required to call the json file from within initialize() not outside
actually, i think i may have gotten it..
it's properly sending out the data to the view now
the lastthing would be to find the objects in the json with manager: true
is that possible to do inside the other functions?
Dovydas Stirpeika
@Giveback007
Feb 09 23:39
well you are calling the json file from within the function, but you are calling the function elsewhere
Lean Junio
@leanjunio
Feb 09 23:39
Is it possible to parse that kind of information?
Dovydas Stirpeika
@Giveback007
Feb 09 23:40
well once you have the data you can do as you wish with it
Lean Junio
@leanjunio
Feb 09 23:43
yeah...I'm just trying to display only specific objects from the promised response that says isManager: true
Dovydas Stirpeika
@Giveback007
Feb 09 23:45
exports.initialize() {
   fs.readFile(`data/fileA.json`, 'utf-8', (err, data) => setDataA(data) )
   fs.readFile(`data/fileB.json`, 'utf-8', (err, data) => setDataB(data) )
}


function setDataA(data) {
  let parsedData = JSON.parse(data)
 // here i use the parsedData 
}

function setDataB(data) {
  let parsedData = JSON.parse(data)
 // here i use the parsedData 
}

exports.initialize()
Lean Junio
@leanjunio
Feb 09 23:45
yep, that's exactly what i have
Lean Junio
@leanjunio
Feb 09 23:54
@Giveback007 Thank you so much for your help. I managed to figure out the last part
CamperBot
@camperbot
Feb 09 23:54
leanjunio sends brownie points to @giveback007 :sparkles: :thumbsup: :sparkles:
:cookie: 339 | @giveback007 |http://www.freecodecamp.org/giveback007