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
Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

uncle blog posted:

We have a frameset of three frames where the content in the child frames will change when the user clicks an a-tag with a href and a target specifying the frame to load the content in. We want to replace the frames with divs. What's the easiest way to get the same dynamic functionality from the current frameset with divs?

Well there are a lot of single page application framework options. But if you want the absolute easiest implementation using native javascript I'd `fetch` the html, parse it, and add the child node you wanted inside of the relevant div element... This is totally untested code I haven't tried it. I'm not 100% sure that the "// populate" section isn't an infinite loop.

code:
window.addEventListener('DOMContentLoaded', function () {
    const links = document.querySelectorAll('a.div-link');
    for (let i = 0; i < links.length; i++) {
        setupLink(links.item(i));
    }
});

function setupLink(link) {
    link.addEventListener('click', function onClick (event) {
        event.preventDefault();
        const url = link.getAttribute('href');
        const target = document.getElementById(link.dataset.target);
        resolveLink(url, target);
    });
}

async function resolveLink(url, target) {
    const html = await fetch(url).then(response => response.text())
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');

    // empty
    while (target.firstChild) {
        target.removeChild(target.firstChild);
    }

    // populate
    while (doc.body.firstChild) {
        target.appendChild(doc.body.firstChild);
    }
}
Then you use links like:

code:
<div id="my-super-div"></div>

<a href="https://www.google.com" data-target="my-super-div" class="div-link">My super link</a>

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

RC Cola posted:

If I had to choose one to learn, should I learn Angular or React?

If for some reason you had to pick only one, React*. But I'd at least do the "Hello World" stuff and make a super simple app in both.


* Because I like it better than Angular, and it seems to be the way the wind is blowing.

Harriet Carker
Jun 2, 2009

In the Bay Area, React is far more in demand than Angular and seems to be growing.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Grump posted:

Ok sorry I have another question.

What's the appropriate way to write debounce logic in React functional components? This works for me, but is there another approach that's more graceful?


I don't think you need that useEffect to make a debounced fetch, but other than that, looks fine to me.

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.

Grump posted:

Spend some time on job boards, figure out which one is more in-demand in your city, and learn that one.

This is good advice.

It also depends what sort of Company you want to work for. The larger the company + the greater chance you're working on internal web-apps, the higher the likelyhood you'll be building something in Angular. Smaller companies with more client-facing stuff will probably prefer React.

The only thing I'll say is Angular is harder, which makes learning React after a bit easier. Learning React does not necessarily make leading Angular easier.

React roles are generally more plentiful, but Angular roles tend to pay more.

Last I checked there was about 1 Angular role for every 3 React roles.

Ape Fist fucked around with this message at 22:43 on May 28, 2019

Vincent Valentine
Feb 28, 2006

Murdertime

Here's the advice I wish I would have gotten:

Learn React.

Learn Angular.

Learn AngularJS(distinctly different from the other)

Then pick which one(s) you like most and apply to jobs for those. If you're truly desperate you also know all the major ones so you can just take what you can get.

It's a lot easier to like a job when it uses the frameworks you actually like. If I could go back in time and only apply to React jobs I would have.

uncle blog
Nov 18, 2012

Nolgthorn posted:

Well there are a lot of single page application framework options. But if you want the absolute easiest implementation using native javascript I'd `fetch` the html, parse it, and add the child node you wanted inside of the relevant div element... This is totally untested code I haven't tried it. I'm not 100% sure that the "// populate" section isn't an infinite loop.

code:
window.addEventListener('DOMContentLoaded', function () {
    const links = document.querySelectorAll('a.div-link');
    for (let i = 0; i < links.length; i++) {
        setupLink(links.item(i));
    }
});

function setupLink(link) {
    link.addEventListener('click', function onClick (event) {
        event.preventDefault();
        const url = link.getAttribute('href');
        const target = document.getElementById(link.dataset.target);
        resolveLink(url, target);
    });
}

async function resolveLink(url, target) {
    const html = await fetch(url).then(response => response.text())
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');

    // empty
    while (target.firstChild) {
        target.removeChild(target.firstChild);
    }

    // populate
    while (doc.body.firstChild) {
        target.appendChild(doc.body.firstChild);
    }
}
Then you use links like:

code:
<div id="my-super-div"></div>

<a href="https://www.google.com" data-target="my-super-div" class="div-link">My super link</a>

This seems easy and neat. Thanks!

Analytic Engine
May 18, 2009

not the analytical engine
If you want a good job and you live in SF, NYC, or another high-paying developer area then for the love of god learn React (and maybe Vue). And for free, you'll know how to use a good framework for personal projects!

(spoken as someone who used the old Angular for too long)
(spoken as someone who knows nobody using the new Angular at a job)

The Merkinman
Apr 22, 2007

I sell only quality merkins. What is a merkin you ask? Why, it's a wig for your genitals!
Where I am is a mix of Angular or Vue depending on the project. Anyway..

One (Angular) Project here, everyone wants to do an SPA (which I think is overrated). However, I can't figure out how 3rd party tags, that should only be on certain 'pages', would work. I can dynamically inject them fine, but I don't know of a way to remove them. Even if I remove them from the DOM once injected, it's still in memory so would still fire.

ddiddles
Oct 21, 2008

Roses are red, violets are blue, I'm a schizophrenic and so am I
As someone who's worked in a large AngularJS codebase, if those are the only jobs in your area, maybe go into construction.

HaB
Jan 5, 2001

What are the odds?

ddiddles posted:

As someone who's worked in a large AngularJS codebase, if those are the only jobs in your area, maybe go into construction.

As someone who has also done the same, I would add that if you find a shop in TYOOL 2019 who is still on AngularJS, you should publicly and loudly shame them and anyone who is responsible for that decision.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I don't think I've ever worked anywhere where I was happy with the codebase. That's why they pay you the big bucks.

Doom Mathematic
Sep 2, 2008

HaB posted:

As someone who has also done the same, I would add that if you find a shop in TYOOL 2019 who is still on AngularJS, you should publicly and loudly shame them and anyone who is responsible for that decision.

It was a fine decision when we made it. Oh hey, our ongoing operation to migrate to React is turning two next week!

HaB
Jan 5, 2001

What are the odds?

Doom Mathematic posted:

It was a fine decision when we made it. Oh hey, our ongoing operation to migrate to React is turning two next week!

Which brings me to another lesson I have learned:

if a shop you are interviewing for is on some old lovely tech stack (AngularJS, JSP, PHP (shudder)), but they are "TOTALLY migrating to a modern stack, that's why we are hiring you!" Unless someone can show you a written project plan / roadmap for the migration, they are lying their butts off, and the job will be a hell of working on their old, lovely stack, while talking a lot about starting the migration any day now, as soon as we can devote some resources to it - which means two things: the job description you read saying it was a React/Vue/Angular (not JS) job was a LIE, and you will torpedo your resume working on that old poo poo.

The last part may not matter to you, but if you regularly work as a contractor, it definitely should. Because lol at sending a resume to a recruiter on which the most recent entry is JSP in TYOOL 2019.

smackfu
Jun 7, 2004

Migration jobs also tend to have requirements like “just make it work the same as the old system” which sucks. But at least the API layer is usually mature.

Lord Of Texas
Dec 26, 2006

HaB posted:

As someone who has also done the same, I would add that if you find a shop in TYOOL 2019 who is still on AngularJS, you should publicly and loudly shame them and anyone who is responsible for that decision.

If you find a shop in TYOOL 2019 who is spending significant resources to refactor their AngularJS app to <insert new cool framework here> without understanding exactly what they're getting out of the refactor... that's what I would walk away from.

Greenfield AngularJS in 2019? Yeah, that's a problem.

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.

Nolgthorn posted:

I don't think I've ever worked anywhere where I was happy with the codebase. That's why they pay you the big bucks.

The ideal situation would be getting to paid to maintain a really expert, well-designed codebase written by people who are better developers than I am. All working in my own long-running project has gotten me is conclusive evidence that I was an even bigger moron in 2014 than I am now.

porksmash
Sep 30, 2008

Bruegels Fuckbooks posted:

The ideal situation would be getting to paid to maintain a really expert, well-designed codebase written by people who are better developers than I am.

Good luck in your search and never lose that optimism.

CharlestonJew
Jul 7, 2011

Illegal Hen
I'm currently working in Angular but a lot of the jobs here in NYC seem to be looking for people with React skills

Thermopyle
Jul 1, 2003

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

Probably all large codebases have lots of stuff that could use lots of improvement. There's not enough smart people to go around for all developers to be The Smart Ones and anyway unavoidable coordination issues would still lead to codebases that are not ideal.

Also, there are lots of large codebases where there were no or very few smart people or the smart people were not empowered to make decisions.

lunar detritus
May 6, 2009


I think all big projects are bound to become messes in the long term. Even if you had the smartest programmer in the world working on it, after six months I bet that programmer could look back and complain about it. Even worse if it's someone new.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
Plus, developers don't live in a vacuum. What to build, what tools to use, and most importantly how long you have to develop it are not always (or in many places, ever) up to them. The place I was just at (and who's code Thermo is now suffering through) everything was entirely written by me and it varies from "well thought out, well documented and tested" to "the boss promised an investor a feature I never heard of was done and the demo is tomorrow at 2".

Doh004
Apr 22, 2007

Mmmmm Donuts...
All codebases are poo poo. Literally the moment you push code out to production it becomes tech debt.

Scope, time and resources. Those are the three levers when developing software and very rarely (if ever) do we have control on all three of those things.

Thermopyle
Jul 1, 2003

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

Lumpy posted:

Plus, developers don't live in a vacuum. What to build, what tools to use, and most importantly how long you have to develop it are not always (or in many places, ever) up to them. The place I was just at (and who's code Thermo is now suffering through) everything was entirely written by me and it varies from "well thought out, well documented and tested" to "the boss promised an investor a feature I never heard of was done and the demo is tomorrow at 2".

Man, the amount of suffering is amongst the least amount of suffering I've had to do when coming into someone elses code.

All of this stuff we're talking about is what makes me vacillate between love and hate of the Coding Horrors thread. I guarantee the best programmers in the world sometimes write horrors themselves because of Reasons, and ridiculing people after the fact with no context feels icky.

On the other hand, I've learned a lot following that thread over the years...

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
e:

teen phone cutie fucked around with this message at 08:53 on Jun 2, 2019

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
Anyone using Apollo and Typescript and has done composed queries where the second query uses the output of the first (using a name on the first)? It's incredibly easy without TS, and I can type my normal queries just fine, but doing a compose like this with TS is driving me up the wall.

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'm getting sick and loving tired of explaining to my back end guys that front end is not like back end and that it doesn't come together the same loving way. It'd be different if we were working inside of something like angular or react where yes, there's a completed framework of items that more or less stays within its own house but given that we don't actually use Front End frameworks the way they're supposed to be used because they're incompatible with our stack/implementation then we have to cobble together a bunch of standards to create our front-end suite, which is fine, but it causes them to have breakdowns when we inherit other .NET Codebases and the front-end has no loving idea how the front-end on the inherited codebase works and we have limited ability to modify it because its a rats nest of different transpilers and precompiling standards then they get frustrated with us asking why it's not the same across the loving board like bro I did not invent front-end web development you need to gently caress off.

ynohtna
Feb 16, 2007

backwoods compatible
Illegal Hen
I like being held accountable for bugs in their (outdated) web browsers or favourite sites.

ndrz
Oct 31, 2003

Grump posted:

Ok sorry I have another question.

What's the appropriate way to write debounce logic in React functional components? This works for me, but is there another approach that's more graceful?

JavaScript code:
import React from 'react'
import { debounce } from 'throttle-debounce';

let debouncedFetch: any;

const Searchbar = props => {

  const [query, setQuery] = React.useState<string>('');
  const [isFetching, setFetching] = React.useState<boolean>(false);
  const [data, setData] = React.useState([])

  const asyncRequest = (value: string) => {
    return props.handleInputChange(value)
      .then(response => {
        setFetching(false);
        setData(response);
      })
      .catch(e => {
        setFetching(false);
        setData([])
      })
  }

  React.useEffect(() => {
    debouncedFetch = debounce(750, false, asyncRequest);
  }, [])


  const _handleInputChange = (value: string, action: any) => {
    setQuery(value);
    if (typeof debouncedFetch === 'function') {
      setFetching(true)
      debouncedFetch(value);
    }
  }

  return (
    <SelectField
      inputValue={query}
      dropDownOptions={data}
      onInputChange={_handleInputChange}
      isLoading={isFetching}
      {...props}
    />
  );
};


Using the module-level debouncedFetch variable prevents you from using this component more than once. I would move that inside the component with a useRef at the very least. If you debounce things frequently, consider a custom hook. Here's a Twitter thread with some examples: https://twitter.com/dan_abramov/status/1060729512227467264?lang=en

Alternatively, you could debounce without a library:

JavaScript code:
  React.useEffect(() => {
    const timeoutId = setTimeout(asyncRequest, 750, query);
    return () => clearTimeout(timeoutId);
  }, [query])
Whenever query changes, React will clean-up the previous effect, and then schedule one with the new query value.

tankadillo
Aug 15, 2006

I was looking into using Electron, and found this electron-store module: https://github.com/sindresorhus/electron-store

My question is: why would I use that (or something similar) instead of IndexedDB?

Assuming that I'm already using an IDB library, and I don't need to read/write data on the main process, I don't care what file format is actually saved to the disk, I don't need encryption, and I want my app to work in browsers, then IDB seems like the obvious choice.

Am I missing something?

Volguus
Mar 3, 2009

tankadillo posted:

I was looking into using Electron, and found this electron-store module: https://github.com/sindresorhus/electron-store

My question is: why would I use that (or something similar) instead of IndexedDB?

Assuming that I'm already using an IDB library, and I don't need to read/write data on the main process, I don't care what file format is actually saved to the disk, I don't need encryption, and I want my app to work in browsers, then IDB seems like the obvious choice.

Am I missing something?

Please, for the love of all that's holy, please rethink your decision to write an Electron app. Most of the time they're bloated monsters that provide very little value for what they're doing. If I need to have 4-5 such apps running, each few GB each, plus a game or something you're killing a 32gb ram machine. Can they be made lean and mean? Sure, VS Code is a relatively good example of this. But how much work and tweaking went into optimizing such app? Do the perceived development savings justify choosing such a monster of a framework? Does it need to be desktop? Can you get away with only web? If it's a hobby project, look into learning new languages/frameworks. It's a great opportunity to do that.

ndrz
Oct 31, 2003

Volguus posted:

Please, for the love of all that's holy, please rethink your decision to write an Electron app. Most of the time they're bloated monsters that provide very little value for what they're doing. If I need to have 4-5 such apps running, each few GB each, plus a game or something you're killing a 32gb ram machine. Can they be made lean and mean? Sure, VS Code is a relatively good example of this. But how much work and tweaking went into optimizing such app? Do the perceived development savings justify choosing such a monster of a framework? Does it need to be desktop? Can you get away with only web? If it's a hobby project, look into learning new languages/frameworks. It's a great opportunity to do that.

It's still in its infancy, but consider revery. It's being built in parallel with OniVim2 by the same person, and looks promising.

Jimlit
Jun 30, 2005



If my boss creates the following less mix-in am I within my rights to savage him in the PR.

code:
 
.tt-upper() {
  text-transform: uppercase;
}

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Jimlit posted:

If my boss creates the following less mix-in am I within my rights to savage him in the PR.

code:
 
.tt-upper() {
  text-transform: uppercase;
}

Only if you replace it with:

code:
.is--upperCased {
  text-transform: uppercase;
}

Thermopyle
Jul 1, 2003

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

Volguus posted:

Please, for the love of all that's holy, please rethink your decision to write an Electron app. Most of the time they're bloated monsters that provide very little value for what they're doing. If I need to have 4-5 such apps running, each few GB each, plus a game or something you're killing a 32gb ram machine. Can they be made lean and mean? Sure, VS Code is a relatively good example of this. But how much work and tweaking went into optimizing such app? Do the perceived development savings justify choosing such a monster of a framework? Does it need to be desktop? Can you get away with only web? If it's a hobby project, look into learning new languages/frameworks. It's a great opportunity to do that.

Ehh, there are problems with Electron. However, there are bloated monstrosities written in every language. There's probably just more of them in Electron-land because a lot of webdevs jump into desktop apps with it without thinking.

One of my most used applications on my PC is the Electron app Notion and it only uses like 250MB of RAM and something like 5% of CPU when I'm actively using it and 0% when it's not active.

All that being said, I'd look into developing PWA's instead of using Electron if you can get away with it.

prom candy
Dec 16, 2005

Only I may dance
Has anyone ported a large client-side React app over to NextJS, or even just plain built a large NextJS app? We're talking about unifying our two React apps into a monolith (for easy style/component sharing and because their required features keep converging) and I was thinking Next might be a good choice because it would take care of code splitting and allow us to host on Now so our users could enjoy SSR and not have to download chunks they don't need. Also certain critical paths do require basic SSR but we handle that with a little express app right now.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

prom candy posted:

Has anyone ported a large client-side React app over to NextJS, or even just plain built a large NextJS app? We're talking about unifying our two React apps into a monolith (for easy style/component sharing and because their required features keep converging) and I was thinking Next might be a good choice because it would take care of code splitting and allow us to host on Now so our users could enjoy SSR and not have to download chunks they don't need. Also certain critical paths do require basic SSR but we handle that with a little express app right now.

No, but if / when you do this, I’d love to hear about your experience, since I see needing to do this in a year or so with an app that’s just getting going now.

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.
So I'm the lead FED at my workplace, head of about 6 guys at varying levels of experience.

I came to the company last year which is an ASP.NET house developing on an ASP.NET CMS Framework called Episerver, my background for the last few years before that was Angular and so I sort of strongarmed the company into using Angular for web-component based solutions inside of the .NET framework and while it works, I'm a little concerned I may have lead us down the wrong path by involving an overly complex front-end framework like Angular to do something that I think React would have probably been way better for. The problem is that I'm obviously a complete loving dunce when it comes to React mostly because I haven't had time to learn it, so I've gotten pigeonholed.

I'd like to maybe start integrating React over Angular for certain areas of our sites but I'm not sure how to pass ASP.NET Razor variables into React.

In an Angular Element, we can simply pass something from ASP.NET into the Angular component pretty easily like this:

code:
<my-angular-element [property]="''@Model.MyASPVariable"></my-angular-element>
This then becomes available inside of the Angular component in a property inside the component class marked with the @Input() decorator.

In React, is the common way of doing this to assign data to the window object and then assign it to state?

Something like

code:
	<script>
		window.myVar = "@Model.MyASPVariable";
	</script>
and then lets say assign that in the React component's constructor or ComponentWillMount() method like:

code:
	myReactMethodConstructorOrWillMountWhoCares() {
		this.setState({
			myVariable = window.myVar,
		})
	}
You could say 'Well why don't you just get the .NET Controller to expose a JSON return type and query the API with Axios then assign that to state?' And that's a good question except my Back End devs are little stupid loving babies who hate doing that for some reason so I almost always have to create some sort of JS object which is built out of Razor variables in my views.

Ape Fist fucked around with this message at 22:25 on Jun 22, 2019

prom candy
Dec 16, 2005

Only I may dance

Lumpy posted:

No, but if / when you do this, I’d love to hear about your experience, since I see needing to do this in a year or so with an app that’s just getting going now.

In looking at it I think I'm going to have to re-engineer a lot of stuff if I want to go down this road. If you think you might need Next a year from now you should probably switch over sooner rather than later before you start implementing solutions that are tough to replicate in Next-land.

Adbot
ADBOT LOVES YOU

prom candy
Dec 16, 2005

Only I may dance

Ape Fist posted:

So I'm the lead FED at my workplace, head of about 6 guys at varying levels of experience.

I came to the company last year which is an ASP.NET house developing on an ASP.NET CMS Framework called Episerver, my background for the last few years before that was Angular and so I sort of strongarmed the company into using Angular for web-component based solutions inside of the .NET framework and while it works, I'm a little concerned I may have lead us down the wrong path by involving an overly complex front-end framework like Angular to do something that I think React would have probably been way better for. The problem is that I'm obviously a complete loving dunce when it comes to React mostly because I haven't had time to learn it, so I've gotten pigeonholed.

I'd like to maybe start integrating React over Angular for certain areas of our sites but I'm not sure how to pass ASP.NET Razor variables into React.

In an Angular Element, we can simply pass something from ASP.NET into the Angular component pretty easily like this:

code:
<my-angular-element [property]="''@Model.MyASPVariable"></my-angular-element>
This then becomes available inside of the Angular component in a property inside the component class marked with the @Input() decorator.

In React, is the common way of doing this to assign data to the window object and then assign it to state?

Something like

code:
	<script>
		window.myVar = "@Model.MyASPVariable";
	</script>
and then lets say assign that in the React component's constructor or ComponentWillMount() method like:

code:
	myReactMethodConstructorOrWillMountWhoCares() {
		this.setState({
			myVariable = window.myVar,
		})
	}
You could say 'Well why don't you just get the .NET Controller to expose a JSON return type and query the API with Axios then assign that to state?' And that's a good question except my Back End devs are little stupid loving babies who hate doing that for some reason so I almost always have to create some sort of JS object which is built out of Razor variables in my views.

You could put data-vars on the element that you're using for your React root and then load it as props when you mount the component:

code:
// Server-rendered template
<div id="react-root" data-my-var="@Model.MyASPVariable"></div>

// Mounting code
const rootNode = document.getElementById('react-root');
const props = rootNode.dataset
ReactDOM.render(<YourComponent {...props} />, rootNode);
Then in YourComponent everything you declared in the data tags will be available as props.

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