Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
My big problem with Typescript is that it's transpiled to Javascript in stead of a real compilation target and will sometimes inherit weird stuff like this scoping and such

Adbot
ADBOT LOVES YOU

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
One thing I will say about Typescript is that its compiler is amazing, way way smaller faster simpler and better than babel. I may even like it more than buble.

necrotic
Aug 2, 2005
I owe my brother big time for this!

Joda posted:

My big problem with Typescript is that it's transpiled to Javascript in stead of a real compilation target and will sometimes inherit weird stuff like this scoping and such

Considering it predates WASM there wasn't really much choice.

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer
I made a small app to make some of my every day tasks easier. I often find myself needing to alphabetize a list, or put in some filenames and wrap them in img tags with urls, or generate an unordered list. It works, though I'm sure I did a lot wrong and was wondering if anyone had any advice: https://codesandbox.io/s/rj1zq9125q

One thing I was confused by was if I change the output to this:

code:
<textarea id="results-area" className="results-area" value=
            {
                listEntries.map((entry, i) => 
                    (showThis === "list") ? (<span className={"item" + i} key={i}>{"<li>" + entry + "</li>"}</span>) :
                    (showThis === "images") ? (<span className={"item" + i} key={i}>{'<img src="/wp-content/uploads/' + entry + '" />'}</span>) :
                    (<span className={"item" + i} key={i}>{entry}</span>)
                )
            }

        />
Then instead of getting the expected results as I would get if that were a normal non-text area element, I get [object Object] repeated as many times as it would loop over the map. I ran into that problem with using "innerHTML" as well, which is what led me to do silly things like hiding the UL opening/closing tag using CSS.

huhu
Feb 24, 2006
First thing, I would generally avoid nested ternary operations, they're a bit hard to understand.

As far as you're actual question, it looks like you're trying to do some weird stuff. You're trying to insert stuff that's not text into a text area.

If you want to display the text output of generating HTML, I'd do something like the following.

code:
     <textarea
        id="results-area"
        className="results-area"
        value={listEntries.map((entry, i) => {
          if (showThis === "list") {
            return (
              `<span className={${"item" + i}} key={${i}}>
                {"<li>" + ${entry} + "</li>"}
              </span>`
            );
          }
	// ...
        })}
      />

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer

huhu posted:

First thing, I would generally avoid nested ternary operations, they're a bit hard to understand.

As far as you're actual question, it looks like you're trying to do some weird stuff. You're trying to insert stuff that's not text into a text area.

If you want to display the text output of generating HTML, I'd do something like the following.

code:
     <textarea
        id="results-area"
        className="results-area"
        value={listEntries.map((entry, i) => {
          if (showThis === "list") {
            return (
              `<span className={${"item" + i}} key={${i}}>
                {"<li>" + ${entry} + "</li>"}
              </span>`
            );
          }
	// ...
        })}
      />

I was running into trouble with the normal if/else statements, and figured if it was only one extra statement it wasn't so bad... but I agree.

I'm also not so strong on the `template literals` and using dollar signs - gotta read up on those!

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

LifeLynx posted:

I was running into trouble with the normal if/else statements, and figured if it was only one extra statement it wasn't so bad... but I agree.

I'm also not so strong on the `template literals` and using dollar signs - gotta read up on those!

In basic usage they are just strings that have whatever is inside the dollar sign curly brackets evaluated and stuck into the string at that spot. Plus they can be multi-line, which is handy!
JavaScript code:
‘I am a string” // I am a string
`I am a string`// I am a string


const e = ‘eight’;
“Adding 4+4 is ${e}” // Adding 4+4 is ${e}
`Adding 4+4 is ${e}`  // Adding 4+4 is 8

“Adding ${4+4} is eight” // Adding ${4+4} is eight
`Adding ${4+4} is eight` // Adding 8 is eight

const someFunc = () => 12
`This is ${ someFunc() > 42 ? ‘greater’ : ‘less’ } than 42` // This is less than 42

const lolNope = “uh oh
  This is a bad idea
  don’t you think” // syntax error 

const superCool = `This will
  work just fine
 and whatnot` // will have newlines in the string 

You can also use them as “tagged templates” which pairs them with a custom parsing function, but I have yet to use them that way.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Fun trivia in case it comes up in an interview for any of you, ternary operations don't evaluate whatever. For example someOperation will never run as long as someBoolean is true:

code:
someBoolean ? 'hello' : someOperation();
For gods sake don't write code that way but still it's interesting.

Nolgthorn fucked around with this message at 10:37 on May 10, 2019

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Lumpy posted:

You can also use them as “tagged templates” which pairs them with a custom parsing function, but I have yet to use them that way.

Huh, I hadn't heard of those before :stare:

necrotic
Aug 2, 2005
I owe my brother big time for this!

Munkeymon posted:

Huh, I hadn't heard of those before :stare:

They can be pretty useful. The thing that shocked me, however, is that tagged templates do not always result in a string: the template function can return whatever it wants and that will be the result.

It made sense once I learned that, but it confused me for a little while at first.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Nolgthorn posted:

Fun trivia in case it comes up in an interview for any of you, ternary operations don't evaluate whatever. For example someOperation will never run as long as someBoolean is true:

code:
someBoolean ? 'hello' : someOperation();
For gods sake don't write code that way but still it's interesting.

FWIW, this is called short-circuit evaluation.

The same mechanism is how come you can do something like (using another language to demonstrate how common short-circuiting is):

Python code:
recently_dead = player or get_npc()

// or maybe

request = request1 or request2
Short circuit operators (which are boolean operations) are probably most useful in languages like JS and python where you have the concept of truthiness or falsiness so you can pick between two different values, though of course they're still useful in other languages like C. For example, you can do a simple inexpensive check to avoid doing an expensive operation...

C code:
if (a != 0 && some_check(b)) {
    im_expensive();
}

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
If I was going to do that in javascript I think I'd use the || operator.

code:
const myThing = activeThing || generateThing();
I can see that.

With the ternary operator I always saw it as a bit of a shortcut selection operation, not that I could (or should) use it to navigate code.

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
What's the benefit of that ${ } syntax over just appending expressions using + like with regular strings?

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


It breaks IE. What more of a benefit do you need?

For a real answer, it makes templating easier.

necrotic
Aug 2, 2005
I owe my brother big time for this!

Dumb Lowtax posted:

What's the benefit of that ${ } syntax over just appending expressions using + like with regular strings?

1) No need to change whatever outer quote if some content inside needs a quote character. Obviously still need to escape ` but that's far less common
2) If you have a lot of interpolation for whatever reason its a lot easier to edit with ${} vs moving around your concatenations
3) You can do multiline strings finally

I dunno, maybe some others?

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Nolgthorn posted:

Fun trivia in case it comes up in an interview for any of you, ternary operations don't evaluate whatever. For example someOperation will never run as long as someBoolean is true:

code:
someBoolean ? 'hello' : someOperation();
For gods sake don't write code that way but still it's interesting.

why would this even be the expected case. that's like expecting an else statement to execute when the if conditional is true.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dumb Lowtax posted:

What's the benefit of that ${ } syntax over just appending expressions using + like with regular strings?

Template literals are easier to read:

JavaScript code:
let a = `
<header>
  <p><a href="${profileUrl}">${name}</a></p>
  <img src="${pictureUrl}" style="max-height: 200px" />
</header>
`
They're the most powerful when you use tagged template literals:

JavaScript code:
> let person = {name: 'John Smith'}; 
> let tag = (strArr, name) => strArr[0] + name.toUpperCase() + strArr[1];  
> console.log(tag `My name is ${person.name}!`)
My name is JOHN SMITH!

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

duz posted:

It breaks IE. What more of a benefit do you need?



:emptyquote:

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

duz posted:

It breaks IE. What more of a benefit do you need?

For a real answer, it makes templating easier.

typescript will let you use template literals with ie if you're so inclined.

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop

Bruegels Fuckbooks posted:

typescript will let you use template literals with ie if you're so inclined.

we're not.

MrMoo
Sep 14, 2000

Lumpy posted:

JavaScript code:
const e = ‘eight’;
“Adding 4+4 is ${e}” // Adding 4+4 is ${e}
`Adding 4+4 is ${e}`  // Adding 4+4 is 8

I think your JS is broken, there is nowhere you will see "8" and not "eight".

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

MrMoo posted:

I think your JS is broken, there is nowhere you will see "8" and not "eight".

Or his browser has become self-aware and is happy to put its own spin on information to be displayed.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Strong Sauce posted:

why would this even be the expected case. that's like expecting an else statement to execute when the if conditional is true.

Yes apparently it works like if else. Congratulations on knowing that before learning it.

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
Every experienced programmer knows what a ternary expression is. My university teaches them in the intro courses too. They are incredibly useful shorthand in the hands of someone who knows how to write clean, readable code. Keep them (and most code) out of any other hands than those though.

RobertKerans
Aug 25, 2006

There is a heppy lend
Fur, fur aw-a-a-ay.

Dumb Lowtax posted:

Keep them (and most code) out of any other hands than those though.

https://hackernoon.com/rethinking-javascript-the-if-statement-b158a61cd6cb

tankadillo
Aug 15, 2006

I've been trying to debug a weird behavior in my React app and haven't had much luck so far.

I'm using useContext and useReducer to access a "global" state object across a bunch of components. Most of the time, but not all of the time, the reducer's "dispatch" function will fire twice. What's weird is that any functions that fire the dispatch will only fire once.

Here's a heavily-trimmed overview of the general code structure:

code:
function reducer(state, action) {
    console.log("This message will almost always appear twice");
    // reducer stuff goes here
}

const Context = createContext();

function Provider(props) {
    const [data, dispatch] =  useReducer(reducer, defaultState);
    return (
        <Context.Provider value={{data, dispatch}}>
            {props.children}
        </Context.Provider>
    );
}

function App() {
    return (
        <Provider>
            <Component />
        </Provider>
    );
}

function Component() {
    const {data, dispatch} = useContext(Context);
    function handleClick() {
        console.log("This message will only appear once");
        dispatch({/* action stuff */});
    }
    render (
        <button onClick={handleClick}>
            Do something
        </button>
    );
}
The problem seems to be similar to what's described on these two Stack Overflow posts, except I'm 99% sure that the reducer function isn't changing, like the SO answers describe, so I'm at a loss.

This wouldn't really be a problem except that for certain actions, like adding an item to a list, firing twice will mean two items get added.

The actual app obviously is a lot more complex and has a lot more code. Any general ideas on what I should be looking for to fix this?

tankadillo fucked around with this message at 18:39 on May 11, 2019

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dumb Lowtax posted:

Every experienced programmer knows what a ternary expression is. My university teaches them in the intro courses too. They are incredibly useful shorthand in the hands of someone who knows how to write clean, readable code. Keep them (and most code) out of any other hands than those though.

I think you're overselling programmer competence here.

ddiddles
Oct 21, 2008

Roses are red, violets are blue, I'm a schizophrenic and so am I
You can pry single line ternary statements out of my cold dead unreadable hands.

code:
const action = someBool ? doThisThing : doThisOtherThing;
action()
Nested ternarys are an early warning sign of clinical depression.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
the do statement is a kinda cool replacement for that. honestly though I wish I could just make a binding constant after a certain point:

JavaScript code:
let foo = -1;
if (this.condition)
    foo = this.calculateSpecialCondition();
if (this.condition2)
    foo = this.tweakThatFoo(this.params, foo);
const foo;
// foo cannot be rebound after this line.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Suspicious Dish posted:

the do statement is a kinda cool replacement for that. honestly though I wish I could just make a binding constant after a certain point:

JavaScript code:
let foo = -1;
if (this.condition)
    foo = this.calculateSpecialCondition();
if (this.condition2)
    foo = this.tweakThatFoo(this.params, foo);
const foo;
// foo cannot be rebound after this line.

Yeah, it's not terribly uncommon for me to be wishing for the same thing.

Roadie
Jun 30, 2013

Suspicious Dish posted:

the do statement is a kinda cool replacement for that. honestly though I wish I could just make a binding constant after a certain point:

JavaScript code:
let foo = -1;
if (this.condition)
    foo = this.calculateSpecialCondition();
if (this.condition2)
    foo = this.tweakThatFoo(this.params, foo);
const foo;
// foo cannot be rebound after this line.

JavaScript code:
const foo = (() => {
  let foo = -1;
  if (this.condition) foo = this.calculateSpecialCondition();
  if (this.condition2) foo = this.tweakThatFoo(this.params, foo);
  return foo;
})();

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

MrMoo posted:

I think your JS is broken, there is nowhere you will see "8" and not "eight".

I think my ability to copy/paste on a phone is not up to snuff..... :smith:

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

tankadillo posted:

I've been trying to debug a weird behavior in my React app and haven't had much luck so far.

I'm using useContext and useReducer to access a "global" state object across a bunch of components. Most of the time, but not all of the time, the reducer's "dispatch" function will fire twice. What's weird is that any functions that fire the dispatch will only fire once.


The actual app obviously is a lot more complex and has a lot more code. Any general ideas on what I should be looking for to fix this?

Read this: https://medium.com/simply/state-management-with-react-hooks-and-context-api-at-10-lines-of-code-baf6be8302c

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Roadie posted:

JavaScript code:
const foo = (() => {
  let foo = -1;
  if (this.condition) foo = this.calculateSpecialCondition();
  if (this.condition2) foo = this.tweakThatFoo(this.params, foo);
  return foo;
})();

creates garbage on current v8, not suitable for hot loop

tankadillo
Aug 15, 2006

Update to my React issue: after doing some (seemingly) unrelated refactoring in the reducer function last night, the problem has mysteriously disappeared. I guess something about the way the reducer was returning new states was causing unnecessary re-firing? Sometimes React seems too “magical.”

The Fool
Oct 16, 2003


Just for funzies, get chrome debugging set up in vscode, set a breakpoint on a random react lifecycle function or hook, then step into it.

huhu
Feb 24, 2006
I'm building an app where one aspect of it is that people rate pieces of content in real time. One person's rating would affect others. I'm leaning towards doing this with websockets. Does this make sense? If so, what's the deal with authenticating a websocket connection? Google is telling me lots of different things. I've already got authentication setup with JWTs and Express I'm wondering if I can reuse the JWT somehow and add it to each websocket message sent or when the connection is established. Or should I be doing something else?

Edit:

Found the snippet below on https://devcenter.heroku.com/articles/websocket-security#authentication-authorization

quote:

When the client-side code decides to open a WebSocket, it contacts the HTTP server to obtain an authorization “ticket”.

The server generates this ticket. It typically contains some sort of user/account ID, the IP of the client requesting the ticket, a timestamp, and any other sort of internal record keeping you might need.

The server stores this ticket (i.e. in a database or cache), and also returns it to the client.

The client opens the WebSocket connection, and sends along this “ticket” as part of an initial handshake.

The server can then compare this ticket, check source IPs, verify that the ticket hasn’t been re-used and hasn’t expired, and do any other sort of permission checking. If all goes well, the WebSocket connection is now verified.
Would this make sense?

huhu fucked around with this message at 01:59 on May 13, 2019

kitten emergency
Jan 13, 2008

get meow this wack-ass crystal prison

huhu posted:

I'm building an app where one aspect of it is that people rate pieces of content in real time. One person's rating would affect others. I'm leaning towards doing this with websockets. Does this make sense? If so, what's the deal with authenticating a websocket connection? Google is telling me lots of different things. I've already got authentication setup with JWTs and Express I'm wondering if I can reuse the JWT somehow and add it to each websocket message sent or when the connection is established. Or should I be doing something else?

Edit:

Found the snippet below on https://devcenter.heroku.com/articles/websocket-security#authentication-authorization

Would this make sense?

SSE might be easier to deal with.

Tanners
Dec 13, 2011

woof

huhu posted:

I'm building an app where one aspect of it is that people rate pieces of content in real time. One person's rating would affect others. I'm leaning towards doing this with websockets. Does this make sense? If so, what's the deal with authenticating a websocket connection? Google is telling me lots of different things. I've already got authentication setup with JWTs and Express I'm wondering if I can reuse the JWT somehow and add it to each websocket message sent or when the connection is established. Or should I be doing something else?

Edit:

Found the snippet below on https://devcenter.heroku.com/articles/websocket-security#authentication-authorization

Would this make sense?

This is like the textbook example for firebase so i would definitely check that out.

E: not that that helps with authentication, guess i should read entire posts

Adbot
ADBOT LOVES YOU

huhu
Feb 24, 2006

uncurable mlady posted:

SSE might be easier to deal with.

What does that stand for?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply