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
gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


Seconding (thirding?) this. Never, ever, have competing sources of truth if you can avoid it. Your future self will thank you. Love thy future self.

Adbot
ADBOT LOVES YOU

tankadillo
Aug 15, 2006

Thanks. I started building the module to manage the data before I began work on the React/UI portion. Without going into a ton of technical detail, it uses a hierarchy of objects that all use data from each other. At the time, it seemed easiest to just include input validation and stuff inside the object methods, and to link them together by assigning them to each other’s properties.

It worked great until I started putting it into React. Then, I needed to keep the data stored in state (or at least, the part of the data relevant to each component). But if I was going to keep using the method functions to (e.g. to input & validate data) then the state had to match the data in the original object instances.

Combined with the fact that I’m a relative newbie at React, this got messy quickly (as I’m sure you figured out).

So you guys have basically confirmed what I was already guessing, which is that I’m doing it wrong :) I’m gonna try try rewriting this into something saner.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
Typescript question! Using refs in React, and I can't get the compiler to shut up about 'Object might be null'

JavaScript code:
const a = useRef(null); // starts out null
// later
<div ref={a} />
I have a hook that wants to get a value from a.current. It always exists when the hook is called, but since it *might* be null, I should code around that, and that's fine! However, any way I can think of that is "nice" to do so it keeps yelling at me.

JavaScript code:
// this yells at me
if(a && a.current && a.current.offsetWidth) {
   console.log(a.current.offsetWidth);
}

// as does this (and every permutation of it I can think off)
if(a !== null) {
  if(a.current !== null) {
    if(a.current.offsetWidth !== null) {
      console.log(a.current.offsetWidth)
    }
  }
}
// etc....
So for now I slapped a temp var typed to 'any' and use that, but I don't want to resort to that.

EDIT: of course typing this out led me to google something else and I have it now...

JavaScript code:
const a = useRef<HTMLDivElement>(null);

// in my hook
const _el = a.current;
if (_el) {
  console.log(_el.offsetWidth);
}

Lumpy fucked around with this message at 21:32 on Apr 18, 2019

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

Lumpy posted:

Typescript question! Using refs in React, and I can't get the compiler to shut up about 'Object might be null'

JavaScript code:
const a = useRef(null); // starts out null
// later
<div ref={a} />
I have a hook that wants to get a value from a.current. It always exists when the hook is called, but since it *might* be null, I should code around that, and that's fine! However, any way I can think of that is "nice" to do so it keeps yelling at me.

JavaScript code:
// this yells at me
if(a && a.current && a.current.offsetWidth) {
   console.log(a.current.offsetWidth);
}

// as does this (and every permutation of it I can think off)
if(a !== null) {
  if(a.current !== null) {
    if(a.current.offsetWidth !== null) {
      console.log(a.current.offsetWidth)
    }
  }
}
// etc....
So for now I slapped a temp var typed to 'any' and use that, but I don't want to resort to that.

EDIT: of course typing this out led me to google something else and I have it now...

JavaScript code:
const a = useRef<HTMLDivElement>(null);

// in my hook
const _el = a.current;
if (_el) {
  console.log(_el.offsetWidth);
}


I don't know React and that seems like the right answer here, but for future reference there's also a non-null assertion for when you know better than the type-checker:

JavaScript code:
a.current = 'hi' // 'Object might be null'
a!.current = 'hi' // everything is peachy

ddiddles
Oct 21, 2008

Roses are red, violets are blue, I'm a schizophrenic and so am I
So I'm doing a deep dive into the serverless app world, seeing what its actually like building something other than a todo list, so I'm making something that lets you sign up, and invite other users to join you in doing...something I havent decided yet.

Going to go for as close to a production ready app as possible using the Firebase ecosystem and have user auth and user data isolation set up, so far the most time consuming part has been building the UI.

I have some opinions on it backed by my complete inexperience:

1. Firestore is ridiculously fast, I have a batch operation on user create that creates a few documents setting up their profile and space and whatnot, and build a react component that does a nice fading animation between progress state text, and the firebase api created and returned the user quick enough to where the loading text barely had time to show

2. Coming from a rails/relational DB world at work, it was kind of hard to wrap my head how to structure data in a nosql DB. So far it seems like you give up on the idea that data shouldnt live in more than one place.

3. Cloud functions are cool, but the cold start times for them on basically any service make them unusable as http endpoints, some people report that their functions can take upwards to 20 seconds to spin up for the first time. The current hack to get around this is to set up cron jobs to ping your cloud functions every minute to keep them warm, which is eh.

That being said, they are really nice when you use them reactively, for example: a user updates their name, in the nosql world that user record is probably duplicated in multiple places, so you set up a cloud function to wait for that change, and let it handle updating the data.

4. This is firebase specific, but the real time capabilities of the DB are really nice, you start to design with it pretty quickly, i dont think i have a save button anywhere yet, its all in the background like google docs.

Heres a recording of firebase auth in action and the its speed: (also, if you are using React, check out react-spring, made the animation stuff super easy)



The actual "backend" code of that is about 30 lines to set up a user and their space or whatever.

code:
export const createUserAndSpace = async ({ userValues, spaceValues }) => {
  let fbUser;

  try {
    fbUser = await signUpWithEmail(userValues);
  } catch (e) {
    throw new Error(e);
  }

  try {
    let batch = db.batch();

    const spaceRef = db.collection('spaces').doc(fbUser.uid);
    batch.set(spaceRef, {
      name: spaceValues.name,
      industry: spaceValues.industry,
      roles: {
        [fbUser.uid]: 'owner'
      }
    })

    let profileRef = db.collection('users').doc(fbUser.uid);
    batch.set(profileRef, {
      name: fbUser.name,
      email: fbUser.email,
      uid: fbUser.uid
    })

    return batch.commit();
  } catch (e) {
    throw new Error(e);
  }
}
Anyway, tldr firebase and the serverless world is pretty nice to work with so far, but I'm just starting. These have been my thoughts while waiting for a fb function to upload. I'll write some more in a couple weeks letting you all know how bad of an idea all this was.

Edit: Also, cypress js is a great testing tool, end to end tested a happy path of the sign up flow in multiple viewports with about 50 lines of js. Imgur compressed that to poo poo, its just runs in a normal chrome browser.
https://imgur.com/a/r7fmofh

ddiddles fucked around with this message at 02:47 on Apr 19, 2019

Hed
Mar 31, 2004

Fun Shoe
Hey it's me again the guy who's liveblogging his redux context issues and while I am a lot smarter about Redux context in React than last time (I am still dumb) I am still having an issue where I have code:

JavaScript code:
// Container component.js
function ConnectableVTCContainer({... , store}) {

    return(
       <Provider store={store}>
           <RemoteAudioPlayer />
           <Connecting />
           ....
       </Provider>
}

// at the bottom
export default function VTCContainer(...props) {
    return (
        <ReactReduxContext.Consumer>
            { ({store}) => <ConnectableVTCContainer {...props} store={store}/> }
        </ReactReduxContext.Consumer>
    )
}
These third-party VTC components are supposed to get wrapped in Provider to get access to the store. I can log out the value of store at the top of my function and see the store, so I believe it's there. However, I'm still getting the
pre:
Could not find "store" in either the context or props of "Connect(RemoteAudioPlayer)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(RemoteAudioPlayer)".


So it's like store isn't available to any of the grandchildren, which is exactly what I thought Provider is supposed to do? And if I add the "store={store}" prop to RemoteAudioPlayer, I'll get the same error message on the next component (Connecting). Is there something obvious I'm missing or a way to debug what is going on? Not really sure why store doesn't seem to be getting wired in when it's otherwise available in my function.

Hed
Mar 31, 2004

Fun Shoe
Also is redux-form still the hotness for form data and verification in projects that already have Redux? I always really liked how Django forms approached form/field validation and handling so if there's anything that's smart like that I'd love to hear it.

prom candy
Dec 16, 2005

Only I may dance
I like Formik for forms. I don't think form state belongs in Redux unless you have a good reason that it needs to be there. I like Redux a lot but I try not to put stuff in there unless I really need it in a bunch of different places in my app.

RE: nosql, this article scared me off of the idea a couple years ago: http://www.sarahmei.com/blog/2013/11/11/why-you-should-never-use-mongodb/

my bony fealty
Oct 1, 2008

I keep seeing this mentioned for a hip new form library https://kozea.github.io/formol/

Idea being its opinionated and greatly reduces markup. Haven't used it and not sure about validation but looks neat. I just do all my own forms and validation tbh, tried Formik and Yup and didn't feel like I needed them.

Ruggan
Feb 20, 2007
WHAT THAT SMELL LIKE?!


prom candy posted:

I don't think form state belongs in Redux unless you have a good reason that it needs to be there. I like Redux a lot but I try not to put stuff in there unless I really need it in a bunch of different places in my app.

I agree, form state almost never belongs in Redux.

It gets real hairy if you fire actions using input onChange. If your state is large enough and you type too fast in an input box you can get some visibly noticeable input lag.

Just put your form state in the form’s container component.

smackfu
Jun 7, 2004

I don’t think the overhead in writing your own form code correctly is that high, but Formik matches up pretty well with my version of “correct” so it is a decent option.

ddiddles
Oct 21, 2008

Roses are red, violets are blue, I'm a schizophrenic and so am I

smackfu posted:

I don’t think the overhead in writing your own form code correctly is that high, but Formik matches up pretty well with my version of “correct” so it is a decent option.

Formik is amazing and wrapping it and its form and field components around your existing inputs is really easy.


A+++ would recommend again.

Ape Fist
Feb 23, 2007

Nowadays, you can do anything that you want; anal, oral, fisting, but you need to be wearing gloves, condoms, protection.
I work in a house full of ASP.NET developers whose attitude towards SPA Frameworks is basically that they're a "solution looking for a problem" which is funny considering that Blazor is exactly that.

Thermopyle
Jul 1, 2003

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

Ape Fist posted:

I work in a house full of ASP.NET developers whose attitude towards SPA Frameworks is basically that they're a "solution looking for a problem" which is funny considering that Blazor is exactly that.

That's what the old guard always thinks about new stuff.

I mean, that doesn't mean new stuff is always good, but I think the ship has sailed on SPA frameworks.

gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


I would rather just become a carpenter than go back to building SPAs without a nice framework.

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.

gbut posted:

I would rather just become a carpenter than go back to building SPAs without a nice framework.

I agree that building an SPA using a framework is better than cobbling together a horrific mass of jquery, but it's also rare that I come across an SPA that I think that it wouldn't have been better off as either an ordinary website that's like a bunch of php/asp, a cellphone app, or a full-on desktop app. Like if you're going to have a poo poo-ton of client side javascript, spa frameworks do help with that, but it's rare that I come across an SPA and think "this is the best possible way this application could have been done."

Dominoes
Sep 20, 2007

Bruegels Fuckbooks posted:

I agree that building an SPA using a framework is better than cobbling together a horrific mass of jquery, but it's also rare that I come across an SPA that I think that it wouldn't have been better off as either an ordinary website that's like a bunch of php/asp, a cellphone app, or a full-on desktop app. Like if you're going to have a poo poo-ton of client side javascript, spa frameworks do help with that, but it's rare that I come across an SPA and think "this is the best possible way this application could have been done."
We can split this into two separate points: client-side code vs server-side, and SPA frameworks vs other client-side approaches.

-Compared to php/asp etc, client-side code can be much faster, due to not having to contact the server: network connection is often the speed limfac. GUIs in particular, are suited for client-side execution.

-One appeal of SPA frameworks is their declarative, functional style. Ie: Describe how the app should behave, rather than the steps of how to do it. Subjective.

-Re phone/desktop apps: Not having to install things can be nice.

Dominoes fucked around with this message at 01:25 on Apr 22, 2019

Ape Fist
Feb 23, 2007

Nowadays, you can do anything that you want; anal, oral, fisting, but you need to be wearing gloves, condoms, protection.

Thermopyle posted:

That's what the old guard always thinks about new stuff.

I mean, that doesn't mean new stuff is always good, but I think the ship has sailed on SPA frameworks.

I should probably gave added that they think Blazor is just loving great because they'll all get to do front end and we won't need to worry about any pesky annoying front end developers ruining everything with javascript and if the front ends want to stick around well I guess they'll all have to learn ASP.NET and C# or gently caress off.

my bony fealty
Oct 1, 2008

Svelte 3 came out and its really cool. Before it felt opaque and poorly documented and now theres a great interactive tutorial that covers the whole API.

rujasu
Dec 19, 2013

Dominoes posted:

-One appeal of SPA frameworks is their declarative, functional style. Ie: Describe how the app should behave, rather than the steps of how to do it. Subjective.

I keep hearing how great this is, but it's tough for me to see the appeal because I just can't wrap my head around how to write code that way. I can easily make a computer do whatever I want with imperative programming and am completely lost with functional and declarative. Is it easy for y'all? Or is it meant to be harder for programmers but offer benefits in terms of code quality?

Thermopyle
Jul 1, 2003

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

It's easier if you can grok it.

gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


The benefits are readability and reusability at the very least.

rujasu
Dec 19, 2013

Thermopyle posted:

It's easier if you can grok it.

gbut posted:

The benefits are readability and reusability at the very least.

Thanks. It's not readable to me at all, but if it works for other programmers who grok it better, that's cool.

dupersaurus
Aug 1, 2012

Futurism was an art movement where dudes were all 'CARS ARE COOL AND THE PAST IS FOR CHUMPS. LET'S DRAW SOME CARS.'

Thermopyle posted:

It's easier if you can grok it.

I didn't really grok the different between imperative and declarative until just now, upon realizing that react et al is declarative

Thanks thread :discourse:

Thermopyle
Jul 1, 2003

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

rujasu posted:

Thanks. It's not readable to me at all, but if it works for other programmers who grok it better, that's cool.

There's a bit of a hump you have to get over if all you're familiar with is imperative style, but I found that once you go over that hump the difficulty slope descends rather quickly.


edit: That link in the above post might be helpful to you.

Thermopyle fucked around with this message at 15:11 on Apr 23, 2019

rujasu
Dec 19, 2013

Thermopyle posted:

There's a bit of a hump you have to get over if all you're familiar with is imperative style, but I found that once you go over that hump the difficulty slope descends rather quickly.


edit: That link in the above post might be helpful to you.

Yeah, I've had it explained that way to me a few times, and it just doesn't take. I think I just have a real aversion to arrow functions (and I had the same reaction to lambda calculus when my prof tried to teach me that years ago) and I'm not sure how much of it is "I don't understand this" vs. "I have an irrational hatred of this." The 3 imperative approaches read fine to me, I understand exactly what is going on, and the 3 "much better" ones are unreadable to me because that drat arrow just doesn't mean anything to me.

HaB
Jan 5, 2001

What are the odds?

rujasu posted:

Yeah, I've had it explained that way to me a few times, and it just doesn't take. I think I just have a real aversion to arrow functions (and I had the same reaction to lambda calculus when my prof tried to teach me that years ago) and I'm not sure how much of it is "I don't understand this" vs. "I have an irrational hatred of this." The 3 imperative approaches read fine to me, I understand exactly what is going on, and the 3 "much better" ones are unreadable to me because that drat arrow just doesn't mean anything to me.

I mean it's really just:

code:

function derp(a) {
  return a * a;
}

===

(a) => { a * a }
That's as simple as I can make it. Using the arrow can affect this binding, but that's already weird poo poo in Javascript, and the arrow doesn't do anything stranger than it already is. It's not perfectly correct form a technical standpoint, but I just think of arrow functions mostly as shorthand. It saves me having to waste 3 lines declaring a function that's really a one-liner, if I'm gonna need to pass that function into something else. Map/Filter/Reduce are REALLY shorthand for performing common operations while looping over an array, with the one big caveat being: unlike a for loop, you cannot exit early. But if I know I want to hit every member of the array, I would MUCH rather write:

code:
const arr1 = [1, 2, 3, 4, 5];

const arr2 = arr1.map(n => n * 2);
than

code:
const arr1 = [1, 2, 3, 4, 5];

const arr2 = [];

for(let i = 0; i < arr1.length; i++) {
  arr2.push(arr1[i] * 2);
}
because good lord.

Even if you want to skip the arrow, map is better:
code:
const arr2 = arr1.map(function (a) { return a * 2; });
map/filter/reduce are your friends, man. Make peace.

gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


Your first example (arrow one) would return undefined. Just fyi.

Vincent Valentine
Feb 28, 2006

Murdertime

It returns correctly. One line arrow functions don't need a return statement.

FormatAmerica
Jun 3, 2005
Grimey Drawer
implicit return, baby! just whatever you do don't wrap that bad boy in curlies or else yeah, undefined.

Ruggan
Feb 20, 2007
WHAT THAT SMELL LIKE?!


Vincent Valentine posted:

It returns correctly. One line arrow functions don't need a return statement.

Wrong

FormatAmerica posted:

implicit return, baby! just whatever you do don't wrap that bad boy in curlies or else yeah, undefined.

Right

Avoid the curly braces for one line implicit return. If you put it in curly braces you need to return something. Also you can omit the parentheses for inputs when you have a single input

No inputs:
const x = () => ‘abc’
const x = () => { return ‘abc’ }

Single inputs:
const x = i => i + 1
const x = (i) => { return i + 1}

Multiple inputs:
const x = (i, j) => i + j
const x = (i, j) => { return i + j }

Destructured inputs:
const x = ({a, b}, c) => a + b + c
const x = ({a, b}, c) => { return a + b + c }

Phone posting god rest my soul so please correct any of these that are wrong

Summit
Mar 6, 2004

David wanted you to have this.
Yeah once you put the brackets there you need to return something. Implicit return only works sans brackets.

prom candy
Dec 16, 2005

Only I may dance
Arrow functions are cool but I like to

export default function MyComponent() {}

in react so that the component names show up properly in dev tools. Also in a module with lots of styled components or helper functions it just makes it easy to find the default export. This has been code tips I'm your host prom candy.

HaB
Jan 5, 2001

What are the odds?

gbut posted:

Your first example (arrow one) would return undefined. Just fyi.

I was just trying to show the syntax equivalent. But yeah, you're right.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

prom candy posted:

Arrow functions are cool but I like to

export default function MyComponent() {}

in react so that the component names show up properly in dev tools. Also in a module with lots of styled components or helper functions it just makes it easy to find the default export. This has been code tips I'm your host prom candy.

You can do this with functional components as well FYI:
code:
const MyComponent = () => <h1>fart</h1>
MyComponent.displayName = 'MyComponent' 
export default MyComponent

Thermopyle
Jul 1, 2003

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

I like typescript a lot, but just for various reasons mostly out of my control I've barely used it in a couple years.

I'm getting back up to speed and it's hilarious how much time I have to spend on getting types correct.

I mean, I know its worth it. I like types, but geeze it took me hours working in a single 30 line file trying to get the types for various third party libraries working right.

gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


That's one my my big issues with TS. You can't cleanly rely on libraries (you can on some) and God forbid you have to convert existing JS codebase. Feels like it would be easier to rewrite from scratch, but that's rarely feasible.

prom candy
Dec 16, 2005

Only I may dance
If there are no types for a third party library I just declare the fucker and move on with my life. Maybe it makes me a bad developer but I'm not afraid to just fall back on any if I feel like I'm wasting time trying to please the type gods.

prom candy
Dec 16, 2005

Only I may dance

Lumpy posted:

You can do this with functional components as well FYI:
code:
const MyComponent = () => <h1>fart</h1>
MyComponent.displayName = 'MyComponent' 
export default MyComponent

Yeah, not worth it just to use arrow functions in this case imo

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
GraphQL / Apollo question! Is there a way to take the Date(s) I get from my query that are ISO 8601 strings and have them converted to js Date objects magically? Obviously running a map on the return gets the job done, but :effort:

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