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
marumaru
May 20, 2013



smackfu posted:

Ran into some code at work recently where I guess someone had just learned about React lazy loading so they made ever single component usage lazy loaded. It worked but whyyyyy.

23,000 1kB bundles is better than 5 10kB bundles!
...right?

Adbot
ADBOT LOVES YOU

Macichne Leainig
Jul 26, 2012

by VG

smackfu posted:

It worked but whyyyyy.

Inadvertent HTTP request load testing, obviously.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
Destroying mobile user's battery life was a firm requirement.

Vincent Valentine
Feb 28, 2006

Murdertime

smackfu posted:

Ran into some code at work recently where I guess someone had just learned about React lazy loading so they made ever single component usage lazy loaded. It worked but whyyyyy.

A guy in Product at my company who is usually extremely competent once said everything should lazy load and when he found out they didn't he started drafting up tickets to deal with it. We pushed back with a lot of vocalized question marks, and he said "Why would we ever not do it?" and when we explained exactly why not to do that, he just said "That's not really a concern, why would we not do this?"

In the end we just said we'll take it up next sprint and never did that, but it was extremely confusing. I can definitely see someone just going "welp, that's what the boss wants. That's what he'll get."

Ruggan
Feb 20, 2007
WHAT THAT SMELL LIKE?!


In React, I see people use both of these styles:

onChange={(value) => { setValue(value) }}
onChange={(value) => setValue(value)}

The first is an anonymous arrow function with an undefined return.
The second is an anonymous arrow function with an implicit return that is used for nothing.

The 2nd has the benefit of readability / less characters used. Is there any disadvantage to the 2nd over the 1st?

Macichne Leainig
Jul 26, 2012

by VG
In ES6 you don't even need the parentheses around the arrow function's parameter if there's only one param, so you can shorten it to:

onChange={value => setValue(value)}

The implicit return isn't used anywhere, and I assume the setValue method comes from the useState hook, where the dispatcher explicitly has a void return type, so it shouldn't ever have any odd side effects from the implicit return.

ynohtna
Feb 16, 2007

backwoods compatible
Illegal Hen
You can also explicitly discard any return result from setValue being passed to the caller by dehumanising and casting yourself into the void:

code:
onChange={x => void setValue(x)}   // no results. just the side effects, ma'am.

prom candy
Dec 16, 2005

Only I may dance
I always do the implicit return because it's prettier

marumaru
May 20, 2013



prom candy posted:

I always do the implicit return because it's prettier

exactly

would react even do anything with the return anyway?

Macichne Leainig
Jul 26, 2012

by VG

Inacio posted:

exactly

would react even do anything with the return anyway?

Send all your datas to Facebook :tinfoil:

tankadillo
Aug 15, 2006

the setValue() never returns anything, does it? (Or rather, it always returns undefined?) AFAIK theres no reason why any of these styles would result in a different behavior.

Tanners
Dec 13, 2011

woof

Ruggan posted:

In React, I see people use both of these styles:

onChange={(value) => { setValue(value) }}
onChange={(value) => setValue(value)}

The first is an anonymous arrow function with an undefined return.
The second is an anonymous arrow function with an implicit return that is used for nothing.

The 2nd has the benefit of readability / less characters used. Is there any disadvantage to the 2nd over the 1st?

You could also just pass setValue in directly, like onChange={setValue}.

However if i do need to wrap in a lambda ill always go for the implicit return

Doom Mathematic
Sep 2, 2008
The disadvantage is that it gives the potentially misleading impression that the return value of setValue is used for anything. In this specific case it probably isn't, but that's something you only know from context, because you know where setValue comes from, you know what it returns (undefined), and you know that return values from the onChange prop are being ignored. None of this is apparent from the code alone. Any of these might be things "you" don't know offhand, or would have to look up, or might even be mistaken about. setValue might not come from useState, it might be handwritten and return any nonsense, and the component in question may well do something important with the return value from onChange - it depends who wrote the code.

The advantage is that you might look more closely at the parameters passed to onChange and the arguments used by setValue and discover that it's safe to just simplify this to onChange={setValue}.

M31
Jun 12, 2012
One example of a case where the second one might break is useEffect, because it has different behaviour depending on a return value existing or not

bvj191jgl7bBsqF5m
Apr 16, 2017

Í̝̰ ͓̯̖̫̹̯̤A҉m̺̩͝ ͇̬A̡̮̞̠͚͉̱̫ K̶e͓ǵ.̻̱̪͖̹̟̕
I like Angular but my company has a pretty huge front end application which is where Angular is actually good, and I've found that React applications can get a bit unruly after they get a bit big :shobon:

lunar detritus
May 6, 2009


bvj191jgl7bBsqF5m posted:

I like Angular but my company has a pretty huge front end application which is where Angular is actually good, and I've found that React applications can get a bit unruly after they get a bit big :shobon:

Yeah, big enterprise-y apps are like the one use case where Angular really shines. I think React (and Vue) can get there too but they require a lot more discipline and hopefully a style guide if you're in a team.

Macichne Leainig
Jul 26, 2012

by VG
I mostly do small scale and hobby-level web development so that's absolutely why I like React/Vue/Svelte etc instead of Angular.

I know a lot of people who work on enterprise scale Angular apps who are happy, though.

bvj191jgl7bBsqF5m
Apr 16, 2017

Í̝̰ ͓̯̖̫̹̯̤A҉m̺̩͝ ͇̬A̡̮̞̠͚͉̱̫ K̶e͓ǵ.̻̱̪͖̹̟̕
I imagine Next/Nuxt can help with bigger react and vue apps a lot

barkbell
Apr 14, 2006

woof
I do Angular as a part of my day job but React on the side. I could see why Next.js became popular for bigger projects.

Macichne Leainig
Jul 26, 2012

by VG
I love Next.js. The file based routing makes so much sense to me, and its pretty easy to set up a very nice feeling static site experience with it.

prom candy
Dec 16, 2005

Only I may dance
Has anyone used the next.js api routes yet? Seems like you can basically build your whole API on next now?

The Merkinman
Apr 22, 2007
Probation
Can't post for 6 hours!
It's always why I found size comparisons between Angular and Vue/React to be poor.

If you're building a large enterprise app, by the time you add on all the other stuff to Vue/React, you're probably at the same size as Angular out of the box.

We use Angular and Vue where I work, though not in the same app. Trying to build a single style guide from it has been fun :rolleyes:. Been looking at Bit.

prom candy
Dec 16, 2005

Only I may dance
I never understood size comparisons because I don't think I've ever worked on a project where there aren't a bunch of images to load that dwarf the size of your initial JS bundle. Also I've never worked on a project that needs to serve people on slow 3G networks as a main target.

I actually spend a lot of time in a semi-remote area in Ontario on <1mbps internet and EVERYTHING is slow. If you're in that situation you're just not expecting the internet to work quickly. If I had a product that was meant to serve those types of users as a main segment then yes, it would be a consideration from the start but as it stands I'm not gonna agonize over 10kb just in case some guy survives a wilderness plane crash and decides he needs to use my sports marketing software.

Ruggan
Feb 20, 2007
WHAT THAT SMELL LIKE?!


Let's say I'm trying to build a flexible table. I want to define columns that go into it in a flexible manner. In react, I might create a columns array:

code:
const columns = [
   {
        title: 'Column A',
        display: (row) => (<div>{row.colA}</div>)
   },
   {
        title: 'Column B',
        display: (row) => (row.colB)
   },
   {
        title: 'Column C',
        display: (row) => { ... some way more complex thing that generates HTML, or maybe even a component ... }
   },
];
Then, in a component, I could loop through the rows, and loop through each column in my definition, and generate the correct display for that row/column.

How would I do this in vue? Specifically, how do I supply a render function or component of some kind to the display property of my column object? Or is there a more "vue" way of doing this?

code:
const columns = [
   {
        title: 'Column A',
        display: (row) => ???
   },
];

HaB
Jan 5, 2001

What are the odds?

Ruggan posted:

Let's say I'm trying to build a flexible table. I want to define columns that go into it in a flexible manner. In react, I might create a columns array:

code:
const columns = [
   {
        title: 'Column A',
        display: (row) => (<div>{row.colA}</div>)
   },
   {
        title: 'Column B',
        display: (row) => (row.colB)
   },
   {
        title: 'Column C',
        display: (row) => { ... some way more complex thing that generates HTML, or maybe even a component ... }
   },
];
Then, in a component, I could loop through the rows, and loop through each column in my definition, and generate the correct display for that row/column.

How would I do this in vue? Specifically, how do I supply a render function or component of some kind to the display property of my column object? Or is there a more "vue" way of doing this?

code:
const columns = [
   {
        title: 'Column A',
        display: (row) => ???
   },
];

The second arg to Vue.component is an object which can contain a render function. You may also want to look at Vue's h() function. I have never done anything that way myself, but Vue does support it.

Relevant docs:

https://v3.vuejs.org/guide/render-function.html#the-dom-tree

Spime Wrangler
Feb 23, 2003

Because we can.

Because I'm lazy and it's easy I usually use bootstrap-vue's tables, which have a lot of flexibility for defining dynamic tables with as-needed custom rendering.

Otherwise the usual vue way (ime) would be to loop over rows and columns in your template and use some property of each column or row with the v-if/v-else-if/v-else directives to choose how to render each cell:

code:
<tr v-for="row in rows">
  <td v-for="col in columns">
    
    // Custom component using row as a prop
    <col-c-component v-if="col.title === 'Column C'" v-bind:row="row" />

    // Custom raw html
    <div v-else-if="col.title==='Column B'" v-html="col.display(row)" />

    // Default rendering of raw value
    <div v-else>
      {{col.display(row)}}
    </div>

  </td>
</tr>
There may be a more elegant solution using render functions & JSX like HaB suggested, but I also haven't used that much. If you're super comfortable with JSX I'd probably spend an afternoon learning the Vue JSX system and try going to town with that. Looks like it requires toolchain modifications, though, so YMMV.

bvj191jgl7bBsqF5m
Apr 16, 2017

Í̝̰ ͓̯̖̫̹̯̤A҉m̺̩͝ ͇̬A̡̮̞̠͚͉̱̫ K̶e͓ǵ.̻̱̪͖̹̟̕
Teams at work got shuffled up for next quarter and we have to pick new names. Nobody had any ideas so I proposed Goku as a joke and now my team at work is called Goku.

gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


It beats User Acquisition, IMHO

HaB
Jan 5, 2001

What are the odds?

bvj191jgl7bBsqF5m posted:

Teams at work got shuffled up for next quarter and we have to pick new names. Nobody had any ideas so I proposed Goku as a joke and now my team at work is called Goku.

My last team that had a name was The Moonrunners. My suggestion. :v:

Ruggan
Feb 20, 2007
WHAT THAT SMELL LIKE?!


bvj191jgl7bBsqF5m posted:

Teams at work got shuffled up for next quarter and we have to pick new names. Nobody had any ideas so I proposed Goku as a joke and now my team at work is called Goku.

Should have said Sonic.

Dev philosophy? Gotta go fast.

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.
There are many problems with Angular but having worked with it for the last 3 years theres still new poo poo I learn every loving day tbh. Some of the advanced patterns are _insanely_ loving good though. Resolvers, injection tokens, component factories, etc. It takes a long loving time to learn how to do the less is more part of Angular but once you do its really really really loving strong.

uncle blog
Nov 18, 2012

I'm implementing a role based access control system in a React app. Bit unsure if my method is a particularly good and/or clean way of doing it.

I have a global context where the user is assigned a role object. That object can look something like this:
code:
carPage: {
	canRead: true,
	canCreate: true,	
	canEdit: (userDistrict, carDistrict) => userDistrict === carDistrict,
	canDelete: false
},
manufacturerPage: {
	canRead: true,
	canCreate: false,	
	canEdit: false,
	canDelete: false
},
Then, on the respective page with an editable form, I have some boolean constants assigned at the root of the file, telling what the user can and cannot do at that particular form. These are set with a useEffect based on the userRole object which gets passed from the global context. These constants are then used to determine if input fields are disabled/delete buttons are visible, etc.
code:
let IS_EDITABLE = false;
let IS_DELETABLE = false;

const CarPage = () => {
	const { userRole } = useContext(AppContext);

	useEffect(() => {
		IS_EDITABLE = userRole.carPage.canEdit(userDistrict, carDistrict);
		IS_DELETABLE = userRole.carPage.canDelete;
	}, [userRole]);

	return (
		<div>
			<span>ENTER CAR NAME:</span>
			<input disabled=(IS_EDITABLE) type="text" />
			(IS_DELETABLE && <button onClick=deleteCar>DELETE CAR</button>) // Seemingly not allowed to write curly braces on the forum
		</div>
	)
}
Are there any obvious shortcomings with this method, or simply a way better way of doing it I should know of?

Ima Computer
Oct 28, 2007

Stop all the downloading!

Help computer.

uncle blog posted:

Are there any obvious shortcomings with this method, or simply a way better way of doing it I should know of?

It's probably not best practice to use top-level/module-scoped variables like that in React. Those variables will be shared by every instance of your component and will persist between renders and mounts/unmounts. And changes to their values also won't trigger re-renders of your component.

You also probably don't want to use useEffect in this instance. I think a useMemo would probably be more appropriate, since your intent is to calculate some value based on another value from your context and there's no benefit delaying that calculation until after the render, which is what a useEffect will do.

What I'd recommend is splitting this permission calculation behavior out into a re-usable hook function that you can call from each page with minimal duplication of code.

JavaScript code:
const usePagePermissions = (pageName, args) => {
  const { userRole } = useContext(AppContext);

  const perms = userRole[pageName] || {};

  return useMemo(() => {
    return Object.fromEntries(
      Object.entries(perms).map((acc, [key, value]) => {
        if (typeof value === 'function') {
          return [key, value(...args)];
        } else {
          return [key, value];
        }
      }, []);
    );
  }, [perms, ...args]);
};


const CarPage = () => {
  const { canCreate, canDelete, canEdit, canRead } = usePagePermissions('carPage', [userDistrict, carDistrict]);
  // ...

Ima Computer fucked around with this message at 16:23 on Oct 6, 2020

uncle blog
Nov 18, 2012

Thanks! That seems like a pretty nifty way.

The Merkinman
Apr 22, 2007
Probation
Can't post for 6 hours!
So a while ago I asked about making a reusable modal in Angular. I ended up building something with this. But now. nnoooope that's not good enough. Now I have to make it where cancel doesn't just dismiss the modal and somehow passes data back to the component that called the modal in the first place. That's the part that I'm struggling with, I can't just do (event)="update()" because the selector (app-modal in the example) for the modal doesn't actually exist!

Jadeilyn
Nov 21, 2004

The Merkinman posted:

So a while ago I asked about making a reusable modal in Angular. I ended up building something with this. But now. nnoooope that's not good enough. Now I have to make it where cancel doesn't just dismiss the modal and somehow passes data back to the component that called the modal in the first place. That's the part that I'm struggling with, I can't just do (event)="update()" because the selector (app-modal in the example) for the modal doesn't actually exist!


You would want to take advantage of the submitCallback in the modal component and service. You can bubble up values through that, and that's how most modal libraries are constructed. I can take a look at his code later if that isn't enough to help you out.

VagueRant
May 24, 2012
Other than hello world and todo lists, are there any go-to ideas for building projects to learn new frameworks? I'm alright dealing with existing code, but I need more practice starting projects from scratch and my mind either goes blank or only comes up with absurdly large ideas.

The Fool
Oct 16, 2003


Instagram/Imgur clone

Url shortener

Flash card player

minato
Jun 7, 2004

cutty cain't hang, say 7-up.
Taco Defender
Instagram clone is a good one, as it exercises the framework's ORM/DB access, file upload/storage, user management, caching, and APIs.

Adbot
ADBOT LOVES YOU

Twerk from Home
Jan 17, 2009

This avatar brought to you by the 'save our dead gay forums' foundation.

VagueRant posted:

Other than hello world and todo lists, are there any go-to ideas for building projects to learn new frameworks? I'm alright dealing with existing code, but I need more practice starting projects from scratch and my mind either goes blank or only comes up with absurdly large ideas.

Searchable database of something scrapeable?

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