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
Roadie
Jun 30, 2013
I've been working on an app built around Vue.js and Typescript, and boy are single-file components and strict typing beautiful once you gently caress around enough to get it all auto-building with Webpack and stuff, and our designer guy tells me that easily scoped styling makes his job way easier. Plus, the clear separation between methods/computed values/props/data is (IMO) way clearer than React's quasi-HTML soup.

Adbot
ADBOT LOVES YOU

Roadie
Jun 30, 2013

Helicity posted:

Our components are pure functions, stateless (except in rare cases), and have minimal/no logic.
See, when I think "component", I think a self-contained thing that can have its own internal operations, state, whatever. For example: toggle button. Click a thing, an animation happens, the internally-held value changes to an appropriate thing, events get passed up if appropriate...

A lovely Vue.js example:
code:
/** ToggleButton.vue */

<template>
  <div class="ToggleButton">
    <input type="radio" name="ToggleButton" value="on" v-model="value"> On
    <input type="radio" name="ToggleButton" value="off" v-model="value"> Off
  </div>
</template>

<script>
  export default {
    props: {
      value {
        type: string,
        default: undefined
      }
    },
    watch: {
      value: function (val) {
        if (val) {
          // put an animation here, or maybe intercept the input event instead
          this.$emit('value', val)
        }
      }
    }
  }
</script>

<style scoped>
// the JS-illiterate design guy's CSS goes here to make it look fancy
</style>
code:
/** In some other file */

<ToggleButton v-model="thisWillBeUndefinedOrOnOrOff"></ToggleButton>

Helicity posted:

https://github.com/erikras/ducks-modular-redux
I'll be honest: to me this is just complete gibberish.

Helicity posted:

Typescript 2.1 is out and has async/await
Async/await is definitely a godsend for a lot of stuff.

Roadie fucked around with this message at 02:44 on Dec 17, 2016

Roadie
Jun 30, 2013

The Wizard of Poz posted:

1) Tapping on a drop down will for some reason cause the keyboard to begin to slide up, before immediately sliding down again.
Is something changing focus (even if it's just to the same element again) immediately after the focus or click event fires?

Roadie
Jun 30, 2013

ddiddles posted:

Thanks man.

I have the bad habit of wanting the first code I write to be the final code I write, so I just sit there wringing my hands thinking "I'm probably doing this wrong", and it stops me from actually getting anything done.

The cure to this one is to do a project where you literally have no idea of how half of it should work when you start out because the client hasn't told you yet and so you just go "gently caress it" and put in stuff that more or less works and go back and change it later (and then again later when the client inevitably changes their mind well after they give you the full spec).

Roadie
Jun 30, 2013

Ahz posted:

Depends on your requirements. Having access to the context doesn't mean you're getting unidirectional data flow like you would with flux/redux patterns. The pattern itself is quite useful for making sense of data changes from all over the place in large apps, and redux pretty much forces you to be a little more strict and explicit about it.

What I'd be happy to see is a react-redux variant that uses the new Consumer stuff to provide the store and dispatch rather than needing a HOC.

Actually, the same thing could go for a lot of stuff that needs HOCs right now.

Roadie
Jun 30, 2013
I'd say go for Redux. It's mostly painless these days with Redux Toolkit to make all the gibberish (for new people) boilerplate generally go away.

Roadie
Jun 30, 2013

uncle blog posted:

Started working on a projected that uses Redux, which I'm not super experienced with. Several pages of the app needs a piece of state that is retrieved by an API call. I'm wondering where I should trigger the action to retrieve the data. Initially I did it on each of those pages, but is it more clevererer to do it in App.tsx or some other place that' ensures it is done before the user navigates anywhere?

Edit:
Currently the dispatch is placed in the router for that subset of pages.

Alternatively: Make a hook that wraps useState and useDispatch, plus something like SWR that makes it easy to pass null to the fetch to have a fetch not happen, to trigger the data retrieval only if the needed data isn't already in the state, then include that hook in each component that needs the data.

You should be making the most of hook reusability, and that includes making stuff with basic caching (don't go overboard on optimizing it) so that instead of needing to specially arrange things you just reference whatever's needed everywhere it's needed and have the hooks do the necessary de-duplication.

Also, if you're not actually doing anything to this state it shouldn't even be in the Redux store in the first place. Just have a custom hook wrapping a fetch call with a suitable cache on it (or again, SWR because it makes cache stuff super easy) and reference that hook in every component that needs the data.

Roadie
Jun 30, 2013

prom candy posted:

That's a good approach but the useState state won't be shared between components in a custom hook so you'll definitely need to either use something that uses context or write your own context.

Maybe that's what you're getting at with the SWR reco but I just wanted to clarify since you mentioned useState as well.

No, you're right there, I had Redux too much on the brain, though there's also other no-config don't-do-it-yourself methods around, like useState-like hooks that sync automatically with LocalStorage/SessionStorage.

But in any case, if all you're doing is a one-way read of data, you should never spend the effort to specially store it, just set up whatever's doing the data retrieval for proper caching and then call it everywhere you need the data.

prom candy posted:

I really like Redux still but I've also been using it since 2015 or so. I don't think it would be worth learning now unless you have an app with a lot of global state, and even that problem is generally mostly solved by the data fetching libraries that manage their own cache. Personally I like RTK Query for that since, surprise, it's built on top of redux. It also makes it really easy to hook into your own reducers, which I've done for slices where I want a highly normalized cache instead of the denormalized one that SWR, react-query, and RTK Query give you out of the box.

Also having used Apollo extensively for data fetching and caching, don't use Apollo.

RTK Query is another good option, though I think their docs are slightly disingenuous about the comparative overhead of "just have a set of data retrieval hooks" for most web apps. I'm working on a thing with about 20 "fetchWhateverData" hooks, each one's about 10 lines (plus type definitions), and the only settings that live in each are ones that would need be individually detailed anyway (e.g. cache this thing for 1 day, cache that thing for 1 minute, etc).

Roadie
Jun 30, 2013

zokie posted:

- use real elements, not divs for everything

zokie posted:

And speaking of divs for everything, why do I see it so much from web devs? Is it some misguided attempt at having a CSS reset?

Have fun trying to do a responsive-friendly layout of navbar elements or related article cards while only using "real" elements and no extra divs in there at all.

HTML/CSS just sucks as a layout engine and even in the best case (flexbox everything, semantic everything, helper tooling for media queries) you often end up with extra wrapper divs for basic visual layout reasons.

Roadie
Jun 30, 2013
SolidJS seems to mostly exist to squeak out performance gains you don't actually need as long as you're writing a React or Vue app correctly in the first place, and the trade-off is that you need special component wrappers and handling for simple JSX use cases like if/else and maps (and even that depending on if something is referencing state or not, which seems like it's begging for more errors than hooks have ever caused).

I feel like if you're going that far you might as well look at something like LiveView instead, which gives you a new paradigm to work with that could enable new and interesting functionality.

Roadie
Jun 30, 2013

novamute posted:

I was going to say "This should be totally fine as long as you're properly handling the cleanup on the effect" but the fact that almost nobody actually does that seems to be the problem they're trying to address at the framework level.

:yeah:

Roadie
Jun 30, 2013

barkbell posted:

I thought the idea was that's not what they wanted useEffect to be used for

e: i dunno what you are supposed to use tho

Use Tanstack Query (formerly react-query). It does all the complicated "doing it right" stuff for you.

Roadie
Jun 30, 2013

prom candy posted:

don't these kinds of libraries all use useEffect under the hood though?

Yes, but they do it correctly.

Roadie
Jun 30, 2013
Just use TanStack Query (ugh, that branding) instead of rolling it yourself. Set refetchInterval to 5000 and forget about the rest. It's already got memoization, deep object comparison, etc included to minimize re-rendering.

Roadie
Jun 30, 2013

Chenghiz posted:

Then this uploading should be performed on your servers. Unless you’re directly responsible for the finances of your employer, your job is to advocate for the security of your systems and sending service account credentials to a browser client is wildly irresponsible.

Yeah, the only sane thing to do here is have your own backend that's a passthrough.

Roadie
Jun 30, 2013
For me, the one big thing still totally missing in Next as compared to Remix is form handling. Not "mutations" or any other fancy poo poo done through frontend JS, just plain form handling that will work right with a form POST from a static page.

Remix by comparison got this right from step 1 with "all mutations are just form submissions".

Roadie
Jun 30, 2013
At this point, the whole "server actions" thing just seems like an overcomplicated, more error-prone version of what Remix already had for a long time.

Roadie
Jun 30, 2013

Splinter posted:

With react-query, any ideas for a re-usable/maintainable way of adding a pause (presumably via setTimeout) in a mutation's onSuccess callback prior to calling queryClient.invalidateQueries() other than manually writing this timeout into any mutations that need this functionality?

The issue I'm running into is parts of this app write/fetch from a 3rd party API (through the app's backend server, the frontend isn't directly making requests to the 3rd party API) and there's a significant (on a programming scale) delay in terms of how long it takes the results of write requests to propagate to the results of GET requests. For instance, after sending a request that should remove an item from at list, it seems to take around 800ms before the GET query that fetches the list actually starts returning the updated list with the removed data. This is long enough that a typical RQ workflow of just calling invalidateQueries in onSuccess results in the queries completing their refetching before the change is reflected in the GET data.

This can be partially alleviated by using setQueryData to update expected queries immediately without relying on a refetch via invalidate, but I'd still like to setup invalidates to work as expected just so other devs on this project to run into the same problem in the future.

Only a portion of the app's queries fetch from this 3rd party API, so this isn't something that needs to be applied to all invalidates.

Just make another hook that wraps useMutation with a wrapped onSuccess call including the delay.

Roadie
Jun 30, 2013

fsif posted:

I use TypeScript in most of my projects and generally like it but I work for an agency and we have to get things out quickly and most of our sites/apps don't need to be maintained for more than the duration of an advertising campaign. Obviously it's a different calculation if you work on a product team.

But like, here's the code I have to write to pass a simple ref into Zustand. The code's hideous and I never needed to revisit past the literal day I wrote it. You can't tell me this saved me time!

TypeScript code:
type StoreState = {
  containerRef: React.MutableRefObject<HTMLDivElement | null> | null;
  setContainerRef: (ref: React.MutableRefObject<HTMLDivElement | null>) => void;
}

export const useStore = create<StoreState>()((set) => ({
    containerRef: null,
    setContainerRef: (ref: React.MutableRefObject<HTMLDivElement | null>) =>
      set({ containerRef: ref }),
})

Here's the version with a bit less boilerplate:

TypeScript code:
import { RefObject } from 'react';
import { create } from 'zustand';

export const useStore = create<{
  containerRef: RefObject<HTMLDivElement>;
  setContainerRef: (ref: RefObject<HTMLDivElement>) => void;
}>((set) => ({
  containerRef: null,
  setContainerRef: (containerRef) => set({ containerRef }),
}));
Pointlessly making separate type declarations is one of those things I see people do over and over with TS and I don't understand why.

Roadie
Jun 30, 2013
The "past projects" thing makes me wonder how they handle people who have, you know, proprietary work stuff and not just a list of 500 open source packages.

Edit: I'm extremely lucky that all the major stuff I did two companies ago is still live on a public platform with the same basic architecture, because everything in between is either B2B services that randos can't see or backend services.

Roadie fucked around with this message at 20:57 on Aug 16, 2023

Roadie
Jun 30, 2013

Combat Pretzel posted:

Angular vs React in this day and age? I can't find a straight answer about this, because each camp is hailing itself to be the best thing ever. IT dept is kinda pushy about getting me to switch from React to Angular.

Angular (whether original or the redesigned v2-and-onward variety) was fundamentally designed for the pre-Webpack era when your build process was "concatenate all the files together and minify the result". Because of this, a significant majority of what it does is just a separate set of mechanisms for doing things that tooling you're using anyway already handles, like handling global state, dependency injection, template parsing, etc.

Vue is conceptually very similar to parts of Angular (two-way bindings, directives, etc), but without all the extra boilerplate that's just part of the build process now. Vue even has some of the same nonsense choices like reinventing JS syntax for filters/pipes.

smackfu posted:

The trick is not getting caught up in a type error and wasting time trying to figure out what magic incantation it wants.

If you're working with your own design and not some outside system, even having non-obvious type errors means you're probably doing something wrong.

Roadie fucked around with this message at 01:50 on Oct 16, 2023

Roadie
Jun 30, 2013
There's zero reason to use RSCs at the moment. Look at the tech again once things stabilize and exist in more than just React canary branches that are entirely undocumented but that they want you to use in production anyway (???!!?!!).

Roadie
Jun 30, 2013
I stll think the whole approach with dictating behavior based on text strings and intermingling client/server code like that is bonkers and a total footgun, and I will be really surprised if the whole RSC structure still exists as-is in 5 or 10 years, let alone becoming popular enough to be the next phase of React in the way that function components and hooks were.

Roadie
Jun 30, 2013
To me the reasonable answer to "I want to split data loading further" isn't RSC, it's taking the already-existing idea of slots and having arbitrary sub-"pages" that each do simultaneous async data stuff.

Adbot
ADBOT LOVES YOU

Roadie
Jun 30, 2013

teen phone cutie posted:

does anyone here use module federation at work?

As I understand it, the target audience is companies like facebook that have 100s of distributed developers working on the same website.

At my work we have 10 front-end devs, and I'm trying to wrap my head around the problems is solves before going to war about why we don't need it.

e: to be clear i'm talking about "micro front-ends" that are a bunch of little apps like the header, footer, and other pieces of a page that all come together at build time to form one big website

The main benefit is that it lets you pull in code from multiple servers and endpoints while still de-duplicating identical dependencies between them, without requiring any special coordination of those different deployments ahead of time other than using module federation. If you don't have multiple separate servers/domains and frontend endpoints, it's just adding more complexity on top of what any bundler already does.

I would personally assume that whoever's proposing to use it for a team of 10 is probably the same kind of resume-driven doofus who tries to use Kubernetes and Helm for absolutely everything.

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