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
Ruggan
Feb 20, 2007
WHAT THAT SMELL LIKE?!


Surgical posting

Adbot
ADBOT LOVES YOU

fsif
Jul 18, 2003

So, a React/hooks-y question that I don't have the proper CS background to Google with the right verbiage.

If I want to pass props down to a component, what is the best way to "freeze" the props value for when the component was first initialized? As a simplified example, let's say I wanted to create a slider component that changes the font size of its parent component. In this component, I also want to include a "cancel" function that reverts the font size back to the value it was before I started messing around with it with the toggle. My best solution was to use useRef() and do something like this…

code:
// Parent.js

const [fontSize, setFontSize] = useState('16px');
const changeFunc = inp => {
  setFontSize(inp);
};
 
<CopyOrWhatever style={{fontSize: fontSize}} /> 
<Slider fontSize={fontSize} changeFunc={changeFunc} />


// Slider.js

const { changeFunc, fontSize } = this.props;
const initialFontSize = useRef(fontSize);

<Slider onChange={(inp) => changeFunc(inp)} />
<CancelButton onClick={() => changeFunc(initialFontSize.current)} />
This seems to work, but I don't know why and I get the sense that this might be something of a hack/anti-pattern. Is there a better way to do what I'm trying to do here?

fsif fucked around with this message at 17:18 on Jul 30, 2019

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
You're overcomplicating things. Just pass down the cancel function from the parent to child and have it set the thing back to 16px.

fsif
Jul 18, 2003

Right, this was a simplified example. The actual work I'm doing pulls a number of variables from a Redux store and contains a lot more logic on how to manipulate the prop when the slider is used.

prom candy
Dec 16, 2005

Only I may dance
Is there a commit action (like a save button) or does cancel function more like an undo? If you're changing values but you don't want them to actually change until the user hits save then I'd copy all the props into local component state and then only run the onChange when you're actually sure the user wants to save their changes. If the cancel button is more like an undo then you're probably on the right path with using a ref, you could also look into some kind of redux undo middleware.

teen phone cutie
Jun 18, 2012

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

fsif posted:

Right, this was a simplified example. The actual work I'm doing pulls a number of variables from a Redux store and contains a lot more logic on how to manipulate the prop when the slider is used.

Dispatch a redux action called “restore defaults” or something?

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.
Is it bad practice to manage the application state from the top level component then pass state and a state mutator method as props to router views? It seems to work nicely and I'm a real baby with react so I'm reluctant to delegate this to Redux just yet

Ruggan
Feb 20, 2007
WHAT THAT SMELL LIKE?!


I don’t see any major problems with that assuming you can keep it simple. Nested routes could get gross.

Are you synchronizing the “router” state with window.location at all?

prom candy
Dec 16, 2005

Only I may dance
You run the risk of firing a lot of unnecessary renders if you're storing a bunch of semi-related application state in one big object and then passing it down through all your components.

Wungus
Mar 5, 2004

I've got a really loving weird browser bug going on that I don't understand. My textarea fields for a project don't seem to apply all font changes until I've put in user input; stylings for the placeholder seem to not be taking effect, and there's nothing at all that targets textarea or its placeholder outside of my specific CSS rules - it's defaulting to a 10px black font until after I've put in. This bug's also not really reproducable in browsers other than Chrome and Safari, which sucks a hell of a lot, as they're the browsers we're targeting for release. I tried asking on StackOverflow if there was any weird properties with textarea fields that might cause this, but I just got yelled at for asking a question in a manner that wasn't "do my homework for me."

I'm super wary about asking specific questions now, because of how aggressive that site was. Does anyone know of any bizarre outliers in Chrome that might be taking precedence over explicit stylings I've put in (and even given !important declarations to, which seem to be completely ignored)? I can give more details but like... frustratingly, I'm not allowed to actually share the whole project to ask for help, and when I pull out all the code that could possibly affect this, I can't reproduce in like jsfiddle or codepen.

e: This is my textarea before user input (note that I've got "color: #fff !important;" as the only rule in like 900 lines of CSS that targets the placeholder)


And this is it after any input is put into the field. It's not even pushing the relatively positioned 'weiter' button down after the field resizes. I'm loving lost as to what is causing this.



e2: Never mind. Asking questions online always leads to solving it yourself. Apparently in this one instance, I needed to put a space between the opening <textarea> and the closing </textarea> despite never in my ten fuckin' years of doing front end work having had this bug occur. This isn't a good fuckin' solution at all, but it'll work good enough for the prototype before we scratch everything and redo this from the ground up as a standalone app.

Wungus fucked around with this message at 15:45 on Jul 31, 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.

prom candy posted:

You run the risk of firing a lot of unnecessary renders if you're storing a bunch of semi-related application state in one big object and then passing it down through all your components.

Well I was going to store primary application state in the top level and pass it to router views which are whole other 'pages', those child state objects don't exist if the route view is currently not in focus surely? I'm not really doing this for a large scale app, just some poo poo I'm loving around with really.

prom candy
Dec 16, 2005

Only I may dance

Ape Fist posted:

Well I was going to store primary application state in the top level and pass it to router views which are whole other 'pages', those child state objects don't exist if the route view is currently not in focus surely? I'm not really doing this for a large scale app, just some poo poo I'm loving around with really.

Oh yeah that's probably fine

The Fool
Oct 16, 2003


I just completed a project using GatsbyJS and am seriously considering just using it as a webpack replacement wherever possible moving forward.

Ruggan
Feb 20, 2007
WHAT THAT SMELL LIKE?!


The Fool posted:

I just completed a project using GatsbyJS and am seriously considering just using it as a webpack replacement wherever possible moving forward.

What was so good about the experience?

The Fool
Oct 16, 2003


Full disclosure, Gatsby uses webpack, but it is preconfigured in a way that agrees with me.

I also like Gatsby starter as a method of scaffolding.

Plus everything else that makes Gatsby a good static site generator, not the least of which is the GraphQL implementation.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
Apollo GraphQL question / possible bug:

Let us say I have a query:

JavaScript code:
GET_STUFF = gql`
  query {
    allStuff {
      name
      id
    }
   selectedStuffId @client
  }
`
It runs in a component, gets data and if there is no selectedStuffId I do this to set a default:

JavaScript code:
client.writeData({
  data: {
    selectedStuffId: 'the-first-id-i-got-back'
  }
});
If I then navigate to another component that calls the GET_STUFF query, it returns an empty object with no errors. If I don't do the write, it does return data. So! What do I do to make it so I can set that value without exploding things?

prom candy
Dec 16, 2005

Only I may dance
Is this using that apollo-link-state package to store local state?

SimonChris
Apr 24, 2008

The Baron's daughter is missing, and you are the man to find her. No problem. With your inexhaustible arsenal of hard-boiled similes, there is nothing you can't handle.
Grimey Drawer

prom candy posted:

The key with context is that unlike Redux, you can't just put all your state in a single "store", you need to have discrete contexts for different things because every component that subscribes to a specific context will get re-rendered any time anything in that context changes.

This is pretty easy to fix, though. I ended up writing my own HOC with a mapContextToProps function, so the inner component only rerenders when the mapped props change. This is basically the same way react-redux handles thing with the connect() HOC, so using Context isn't much different. Redux technically also rerenders any component that subscribes directly to the store, which is why you you pipe the store through a higher order component.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

prom candy posted:

Is this using that apollo-link-state package to store local state?

It's using the ApolloClient from apollo-boost

prom candy
Dec 16, 2005

Only I may dance

SimonChris posted:

This is pretty easy to fix, though. I ended up writing my own HOC with a mapContextToProps function, so the inner component only rerenders when the mapped props change. This is basically the same way react-redux handles thing with the connect() HOC, so using Context isn't much different. Redux technically also rerenders any component that subscribes directly to the store, which is why you you pipe the store through a higher order component.

React-redux 7 moved back to doing direct subscriptions after using context in 6.x, and react-redux 7.1 includes hooks so you don't actually need to use the HoC anymore. I think they had performance issues in 6.x -- https://github.com/reduxjs/react-redux/releases/tag/v7.0.1

Lumpy posted:

It's using the ApolloClient from apollo-boost

Oh okay yeah Apollo boost includes Apollo-link-state, which is what that @client directive is using. I tried using Apollo-link-state about a year ago and gave up after a couple days as I found it was buggy, unpredictable, and difficult to debug. At the time there were a couple of those big "hey this super common use case doesn't work" type issues on GitHub with no resolution. Maybe it's better now but based on your bug also maybe not? I'm just using Apollo for data and redux for local state, and thunks that call my Apollo client directly when I need to mix both. It would probably be cleaner to use Apollo for everything but I just was tearing my hair out and gave up.

Edit: here's more on React-redux v6's perf issues https://github.com/reduxjs/react-redux/issues/1177

prom candy fucked around with this message at 02:58 on Aug 3, 2019

RC Cola
Aug 1, 2011

Dovie'andi se tovya sagain
Cross post from the newbie hiring thread :

Hey friends, I was just offered an interview as a Front-End JavaScript Developer. They asked me what I knew about D3. I was honest and said 3 weeks worth and that I was working on a MERN project that involved scraping data from Wikipedia and displaying it with D3.js. The interviewer was a developer and told me my resume didn't reflect any of these skills. He said touch it up, and send a D3 project for him to look at. They mainly need someone to take data given to them and to be able to display it in a way clients and non developers can understand.

Is there any resources that any of you know of that can help me learn D3.js better besides the documentation that I've already read?

Ruggan
Feb 20, 2007
WHAT THAT SMELL LIKE?!


https://bl.ocks.org/mbostock

Analytic Engine
May 18, 2009

not the analytical engine
This is the best book out there

https://www.amazon.com/D3-js-Action-Data-visualization-JavaScript/dp/1617294489

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
Anyone use Cypress.io for testing? If so, do you know if it's possible to have a plugin write to a global object? Example:

JavaScript code:
//main.js
const thing = module.exports.thing = {};
cypress.run({ spec: 'spec.js' })
  .then( _r => {
    console.log("thing is:", thing);
  });



//spec.js
describe("stuff", () => {
  it("does", () => {
    cy.task("startTimer", "wheee");
    ...
    cy.task("endTimer", "wheee");
  })
})



// plugins/index.js
const thing = require('../main').thing;
module.exports = (on) => {
  on("task", {
    startTimer(action) {
      thing[action] = 'start'
    }
    endTimer(action) {
      thing[action] = 'ended'
      // logging `thing` here shows both start and end exist
    }
}
No matter what, when main.js logs that object, it's empty. I've tried moving the import inside the function, moving the export, exporting it as a function that returns the object, etc. I suspect that cypress is doing something clever that makes this impossible. That or I am missing something very, very obvious. Odds are 50/50 on each.

Hed
Mar 31, 2004

Fun Shoe
What would someone use in React to interact with my own REST endpoints in mid-2019?

I have a RESTful backend that uses token auth that my (TypeScript) React app would love to consume and I see old tutorials of people using axios, fetch, and everything else. I feel like I'm missing good documentation or just not searching correctly. Ideally it would cover best practices to put login / logout, store the token key, handle token updating, and walk through implementing a few basic GET/POST/PUT transactions, but I'll take what I can get.

prom candy
Dec 16, 2005

Only I may dance
Fetch but I wrote my own wrapper functions for get and post that attach the token to the request. I usually have a folder called "api" with functions for each endpoint, that way my api stuff isn't super coupled to my view layer.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

dantheman650 posted:

But the time zone setting is just a global setting and all events will use it for any particular user. I don’t think it should be too bad.

This will bite you.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

prom candy posted:

styled components is cool but also check out tailwind, I have a huge boner for utility first css right now (probably because I have yet to build an unmaintainable mess with it like I have with every other CSS approach)

I will never understand utility first CSS. Surely all you've done is moved inline styles to a different HTML attribute?

prom candy
Dec 16, 2005

Only I may dance

a hot gujju bhabhi posted:

I will never understand utility first CSS. Surely all you've done is moved inline styles to a different HTML attribute?

quote:

Isn't this just inline styles?

It's easy to look at this approach and think it's just like throwing style tags on your HTML elements and adding whatever properties you need, but in my experience it's very different.

With inline styles, there are no constraints on what values you choose.

One tag could be font-size: 14px, another could be font-size: 13px, another could be font-size: .9em, and another could be font-size: .85rem.

It's the same blank canvas problem you face when writing new CSS for every new component.

Utilities force you to choose:

Is this text-sm or text-xs?

Should I use py-3 or py-4?

Do I want text-dark-soft or text-dark-faint?

You can't just pick any value want; you have to choose from a curated list.

Instead of 380 text colors, you end up with 10 or 12.

My experience is that building things utility-first leads to more consistent looking designs than working component-first, as unintuitive as it might sound at first.

(from this article)

RobertKerans
Aug 25, 2006

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

a hot gujju bhabhi posted:

I will never understand utility first CSS. Surely all you've done is moved inline styles to a different HTML attribute?

Sort of, but it's a. configurable in a single place, b. extremely constrained, as prom candy said. I think I posted that same link a few months ago, as was pretty skeptical at the time, but it makes building stuff ridiculously fast. Also [caveat that this is only 3 months into an experiment] I feel like this is the best way to approach styling React Native, it's been a helluva lot more pleasant to work with than any other approach:

JavaScript code:

export default Stylesheet.create({
  dark: { color: "#foo" },
  light: { color: #bar" },

  bg_dark: { backgroundColor: "#foo" },
  ......
});

// then somewhere else

import s from "./Styles";

export const Fart = (props) => (
  <View style={[s.bg_dark, s.rounded, s.p_sm]}>
    <Text style={[s.light, s.bold]>Fart</Text>
  </View>
);


:shrug:

RobertKerans fucked around with this message at 14:59 on Aug 11, 2019

Volguus
Mar 3, 2009
Does anyone have any experience with WebRTC?
What I need: to send to a server the video stream from the client's webcam, process that stream (some object recognition), and send back to the client data (json) about what was recognized in the image so that the browser can then display it in some form. All of this should happen live, ideally at 30FPS.
Do I need WebRTC for this? Can it be accomplished via just a websocket to the server? Or would it be better to just look if I can move the object recognition part to the browser via WASM and just do it on the client's machine? Though, now we use tensorflow and CUDA for this , so I don't think they can be moved in the browser.
And if WebRTC would be better suited for this live stream, if the server is behind a NAT, does it need a TURN or STUN server? Can't everything just work with just port forwarding?

teen phone cutie
Jun 18, 2012

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

Hed posted:

What would someone use in React to interact with my own REST endpoints in mid-2019?

I have a RESTful backend that uses token auth that my (TypeScript) React app would love to consume and I see old tutorials of people using axios, fetch, and everything else. I feel like I'm missing good documentation or just not searching correctly. Ideally it would cover best practices to put login / logout, store the token key, handle token updating, and walk through implementing a few basic GET/POST/PUT transactions, but I'll take what I can get.

Axios is a good wrapper around XMLHTTPRequests

https://github.com/axios/axios

my bony fealty
Oct 1, 2008

Grump posted:

Axios is a good wrapper around XMLHTTPRequests

https://github.com/axios/axios

superagent is another good one. I usually just end up using fetch these days but axios is probably the "best" in terms of ease-of-use and its api.

for auth stuff using context is a good idea (assuming you're not already using a global-capable state manager) - set up a context just for auth/login stuff, makes it easy for all of your components to access the token and whatever else.

I'm all hooks now so all my auth stuff in the last thing I built that needed it was handled in useEffect() hooks, which are great because they let you tie side effects to relevant state instead of (imo arbitrary) lifecycle methods.

I don't know if you're going to find a tutorial that covers anything that comprehensively, at least for free. maybe go into some detail here about what exactly you're trying to do?

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
I have this issue where the latest jest can't parse `.mjs` files which is a problem because ramda (one of my node_modules) has an `.mjs` file that hasn't been converted to commonjs, so I'm getting `unexpected token export`

Is there an easy solution to this with babel?

I've been looking at this but as far as I can tell, it doesn't convert node_module src files

https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION
Thanks for the responses re: utility first CSS. I have a great deal of respect for the front-end genuises here so I might give it more of a chance and see how I find it. Your responses make a lot of sense, thanks!

prom candy
Dec 16, 2005

Only I may dance
It's really cool once you get into it. It makes experimentation super easy as well. I had to play around with the layout of a form yesterday and it made it super fast to just start adding elements and classnames without having to open a separate CSS file or keep jumping back and forth between parts of my file, and also to not have to go "okay is this thing a FormRowWrapperInner or an InnerFormRowWrapper or a Wrapper--form-row-inner" or whatever. It was just "flex items-center" and then when the layout I was trying looked like poo poo it was deleted.

Queen Victorian
Feb 21, 2018

I started writing a reply about the utility-first CSS a couple days ago and then forgot. I’m firmly in the semantic-first camp. This is probably because I started out as a designer and spent (and still spend) lots of time in Dev Tools tinkering with the output to test styles/diagnose issues - if everything is predominantly semantic, I know exactly where I am and it’s easy to find things, but if it’s a jumble of utility classes (or worse, procedurally generated gibberish classes), then it’s a pain in the rear end. I’ve also found, in my personal experience, that semantic-first lends itself better to design overhauls because you can more easily stick to the style sheets and not have to futz around with all the markup in all the components.

Our newest dev came with a stubborn insistence on utility-first (despite the convention here being semantic-first), and also has a poor understanding of CSS, so he doesn’t even do good utility-first markup. Despite the fact that his markup style flies in the face of the rest of our code and is bad, I’m just told to stop protesting and merge his poo poo anyway.

Good thing I’m leaving next week.

prom candy
Dec 16, 2005

Only I may dance
I think the utility first thing pairs really nicely with a library that provides components, like React. I can use my React devtools to get a picture of how the page is laid out semantically and then flip over to the elements panel if I want to screw around with things. I also don't tend to do that much editing in devtools anymore thanks to hot reloading. The other benefit of a component library with utility first is that you can just extract components that are a combination of markup and styles. Good explainer on that here: https://tailwindcss.com/docs/extracting-components/#extracting-html-components

You're the same poster that was having trouble being taken seriously at work a while back right? Glad to hear you're getting out of there!

Queen Victorian
Feb 21, 2018

prom candy posted:

You're the same poster that was having trouble being taken seriously at work a while back right? Glad to hear you're getting out of there!

Yup that was me. And thanks! Not only am I getting out of there, I’m getting out of there because I got poached by another company that wanted me for my data visualization skills (and more generally because I can design and also code). :sun:

That was a much-needed boost for my totally battered self esteem.

They also told me that my take-home coding exercise (a very reasonable and well-designed one involving React/Redux) was one of the better ones and clearly demonstrated I knew how to program and write a stylesheet, and they liked how clear and organized it was. Nice change from being shat on about how slow and bad I am at all this newfangled front-end stuff.

Adbot
ADBOT LOVES YOU

gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


Congratulations! I've been struggling with a similar issue as I come from design background and have been relegated to backend in the last few years. "Senior engineer" "value" crap and all that. Hoping to get back into frontend, but it will be hard to find something better where I live.

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