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
huhu
Feb 24, 2006
The job wants to pay me to do Node/Express soooo. They're early enough I could be like, hmm how about Django?

Another question - is one way better than the other? I have data like so that I want to put into a redux store:

code:
[
  {
    foo: 'bar',
    id: 1,
  }
]
Option 1: Reformat the structure to look like:
code:
{
  1: {
    foo: 'bar',
    id: 1,
  }
}
So I can easily get by id.

Or option 2: Search through the list of elements each time for id=1.

Adbot
ADBOT LOVES YOU

kitten emergency
Jan 13, 2008

get meow this wack-ass crystal prison
1 isn't valid JSON, so probably 2.

The Fool
Oct 16, 2003


.

Roadie
Jun 30, 2013

huhu posted:

The job wants to pay me to do Node/Express soooo. They're early enough I could be like, hmm how about Django?

Another question - is one way better than the other? I have data like so that I want to put into a redux store:

code:
[
  {
    foo: 'bar',
    id: 1,
  }
]
Option 1: Reformat the structure to look like:
code:
{
  1: {
    foo: 'bar',
    id: 1,
  }
}
So I can easily get by id.

Or option 2: Search through the list of elements each time for id=1.

Option 1. Use normalizr to convert to/from nested/arrayed API structures as necessary.

Roadie fucked around with this message at 06:06 on May 31, 2018

huhu
Feb 24, 2006

Roadie posted:

Option 1. Use normalizr to convert to/from nested/arrayed API structures as necessary.

Ooh I like this thanks!

Another question. I stopped working on a React project last night that worked when I went to bed. This morning I'm getting errors from npm. I had to do an rm -rf node_modules and npm i. What could have possibly happened between last night and now for this to happen?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

huhu posted:

The job wants to pay me to do Node/Express soooo. They're early enough I could be like, hmm how about Django?

Another question - is one way better than the other? I have data like so that I want to put into a redux store:

code:
[
  {
    foo: 'bar',
    id: 1,
  }
]
Option 1: Reformat the structure to look like:
code:
{
  1: {
    foo: 'bar',
    id: 1,
  }
}
So I can easily get by id.

Or option 2: Search through the list of elements each time for id=1.

Option 3:

JavaScript code:
state = {
  things = [ 1, 2 ],
  thingsById = {
    1: { foo: 'bar', id: 1 },
    2: { boo: 'blah', id: 2 },
  }
}
Which is sort of what what normalizer does.

Thermopyle
Jul 1, 2003

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

huhu posted:

Ooh I like this thanks!

Another question. I stopped working on a React project last night that worked when I went to bed. This morning I'm getting errors from npm. I had to do an rm -rf node_modules and npm i. What could have possibly happened between last night and now for this to happen?

ghosts

or

Thermopyle fucked around with this message at 17:25 on May 31, 2018

necrotic
Aug 2, 2005
I owe my brother big time for this!

huhu posted:

Ooh I like this thanks!

Another question. I stopped working on a React project last night that worked when I went to bed. This morning I'm getting errors from npm. I had to do an rm -rf node_modules and npm i. What could have possibly happened between last night and now for this to happen?

Next time post the errors. But the answer is almost always: npm is trash fire.

Dominoes
Sep 20, 2007

Is Javascript able to use binary code, or execute code from other languages in the browser? (Not talking WASM) I'm asking due to recent trouble installing a package (numjs) due to it requiring an old version of Python, or a node version that it has a binary for. (Both of those situations are relevant to my question.) Also unsure how the magic in WebGL (eg accessing GPU hardware from JS) or React is done.

Chenghiz
Feb 14, 2007

WHITE WHALE
HOLY GRAIL

Dominoes posted:

Is Javascript able to use binary code, or execute code from other languages in the browser? (Not talking WASM) I'm asking due to recent trouble installing a package (numjs) due to it requiring an old version of Python, or a node version that it has a binary for. (Both of those situations are relevant to my question.) Also unsure how the magic in WebGL (eg accessing GPU hardware from JS) or React is done.

No, and I'm fairly sure that library is meant to be run in node.js, not in the browser. NPM can be confusing because some portion of the libraries are server-only (node.js only) and authors don't often do a good job at making it clear when that's the case.

Roadie
Jun 30, 2013

Dominoes posted:

Is Javascript able to use binary code, or execute code from other languages in the browser? (Not talking WASM)

Not to be a jerk, but I think you should really brush up on the basics of how Javascript works and on the differences inherent in Node-specific APIs.

mystes
May 31, 2006

Chenghiz posted:

No, and I'm fairly sure that library is meant to be run in node.js, not in the browser. NPM can be confusing because some portion of the libraries are server-only (node.js only) and authors don't often do a good job at making it clear when that's the case.
The page dominoes linked says near the top that it runs in the browser.

necrotic
Aug 2, 2005
I owe my brother big time for this!
Yes the bower package (lol) is for the browser, the npm package is for node.

Dominoes
Sep 20, 2007

Chenghiz posted:

No, and I'm fairly sure that library is meant to be run in node.js, not in the browser. NPM can be confusing because some portion of the libraries are server-only (node.js only) and authors don't often do a good job at making it clear when that's the case.
That makes sense

huhu
Feb 24, 2006
Curious if anyone using React has any favorite libraries for it? The biggest ones I currently use are Axios, Styled Components, Redux, Webpack, Material UI, babel and the associated libraries required to connect them to React. I'm starting a new project and thought it would be a good time to see if there's anything out there that would augment this list.

porksmash
Sep 30, 2008
I've fallen in love with lodash FP since my last post so I'd add that to the list. Also redux-saga.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Dominoes posted:

Is Javascript able to use binary code, or execute code from other languages in the browser? (Not talking WASM) I'm asking due to recent trouble installing a package (numjs) due to it requiring an old version of Python, or a node version that it has a binary for. (Both of those situations are relevant to my question.) Also unsure how the magic in WebGL (eg accessing GPU hardware from JS) or React is done.

The magic of WebGL is that it's an API implemented by the browser, in C++, which can already access your GPU.

React is just an algorithm implemented in JavaScript. All it does is manipulate data objects and doesn't require any external hardware, so it doesn't need any native code.

Thermopyle
Jul 1, 2003

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

Dominoes posted:

Is Javascript able to use binary code, or execute code from other languages in the browser? (Not talking WASM) I'm asking due to recent trouble installing a package (numjs) due to it requiring an old version of Python, or a node version that it has a binary for. (Both of those situations are relevant to my question.) Also unsure how the magic in WebGL (eg accessing GPU hardware from JS) or React is done.

There's several blog posts out there that walk through implementing the basics of React on your own in vanilla Javascript. I highly recommend reading those.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

huhu posted:

Curious if anyone using React has any favorite libraries for it? The biggest ones I currently use are Axios, Styled Components, Redux, Webpack, Material UI, babel and the associated libraries required to connect them to React. I'm starting a new project and thought it would be a good time to see if there's anything out there that would augment this list.

I mainly just use: redux, redux-thunk, redux-first-router, reselect in my projects. I just use the built-in fetch for network stuff, and I personally find UI component libraries to be more work than helpful (not that they are for you though!)

Reselect is a wonderful, wonderful thing. As is redux-first-router.


porksmash posted:

I've fallen in love with lodash FP since my last post so I'd add that to the list. Also redux-saga.

I would love to hear how you are using lodash FP (maybe with some examples??) if you have the time and inclination to do so.

TheFluff
Dec 13, 2006

FRIENDS, LISTEN TO ME
I AM A SEAGULL
OF WEALTH AND TASTE

Lumpy posted:

I would love to hear how you are using lodash FP (maybe with some examples??) if you have the time and inclination to do so.
I'm using lodash-fp a lot in a current project, and while I like it a lot, it's pretty confusing to junior devs (particularly the currying bits), the documentation is very terse, and last time I looked there weren't any even remotely complete TypeScript typings files for it. It is very good though and I recommend it if you're at a place that has functional staffing and you don't need to introduce some FNG who barely understands the difference between a class method and an instance method to the project every three months.

In this current project we pretend it's the standard library and use it everywhere we can, so instead of someArray.map(item => item.id), we prefer _.map(_.get('id'), someArray). For mangling arrays and/or objects in various ways I've found function composition with _.flow to be pretty handy, and we also use currying in some places to prepare functions to pass around as predicates and the like, or to things that expect a function that takes only a callback. I dunno how to sell it or explain it really - if you're used to functional programming you'll probably love it and use it everywhere, and if you don't you'll probably think it's just pointless.

One quite practical upside though is that the argument capping/fixed arity stuff does avoid a whole bunch of minor annoyances/potential bugs with passing functions that take optional arguments as iterators to map/filter etc. The classic example of this is of course parseInt, like

code:
['0', '1', '2', '3'].map(parseInt); // returns [ 0, NaN, NaN, NaN ]
_.map(parseInt, ['0', '1', '2', '3']); // works as expected because the iterator function is only passed one argument

porksmash
Sep 30, 2008

Lumpy posted:

I would love to hear how you are using lodash FP (maybe with some examples??) if you have the time and inclination to do so.

I'm using it to filter arrays of objects based on redux state. I'm still a javascript noob so I have no idea if I'm doing something neat or creating a horror - but it works! You can specify deeply nested object attributes to filter on. I need to rework it a little bit to handle deeply nested arrays of objects - the entityValue() in filters.js recurses itself and returns an array of all object values in that nested array, but the filter code does not handle it properly.

Here's the code that provides the filtering functionality. It's used in my redux selectors here

To specify the object path and conditionals I borrowed Django's ORM double snake case syntax for traversing related objects and/or applying conditionals because I love Django.

code:
// Example
const dummy_objects = [
    { a: { b: 2 }, c: 5 },
    { a: { b: -50 }, c: 9 },
    { a: { b: 6 }, c: 22 },
];
const filter = [
    {	// a.b >= 2
	attribute: 'a__b__gte';
	value: 2
    }
];

console.log(applyFilters(dummy_objects, filter));
// prints first and third object in array
You can see it in action here: https://alpha.swarfarm.com/bestiary. Use the redux devtools to see what the filter state looks like.

Edit: The second I hit post I realized I could probably refactor the filter into an object and use the object/comparator string as a key and the value as an object like this:

code:
const filter = {
    a__b__gte: 2
}

porksmash fucked around with this message at 17:43 on Jun 5, 2018

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
JavaScript code:
export interface State {
  foo: string;
  bar: number
}
class MyComponent extends React.Component<Props, State> {
  state: State = {
    foo: 'hello',
    bar: 3,
  }

  // ensure we're only allowed to update state that exists in this component
  updateState = (key: keyof Partial<State>, value: any) => {
    this.setState({ [key]: value });
  }

  render(){
    <SomeOtherComponent
      updateParentState={this.updateState}
    />
  }
}

-----------------------------------

import {State as ParentState} from './MyComponent';

interface Props {
  updateState: (key: keyof Partial<ParentState>, value: any) => void
}
const SomeOtherComponent = (props) => {
  return (
    <Button 
      // the below should give an error because it's not part of
      // the State types for the parent component
      // ...but it's not????
      onClick={() => props.updateState('nonsense', 1000)}
    />
  )
}
I have a newbie TypeScript/React question. How come the onClick for SomeOtherComponent isn’t yelling at me? To preface, I know this is a bad programming pattern, but I want pass down an update state function, so that my child component can update the parent’s state, but want to make it safe so that the only state that can be updated is state keys that already exist.

How would I go about fixing the above?

teen phone cutie fucked around with this message at 22:02 on Jun 5, 2018

huhu
Feb 24, 2006
Would love some feedback on this code I wrote for my redux store and to see if there are any pitfalls or ways to improve on it. For each site I make I've always felt like communicating with the API was a bit sloppy so I tried to write a better request function that handles the actions and actions creators and then the rest of the store is only responsible for creating reducers for the requested data.

getRequest.js
code:
import axios from 'axios';

import { API_URL } from '../../../../constants';

export const getRequestStart = resource => ({
  type: `GET_${resource}_START`,
});

export const getRequestSuccess = (resource, data) => ({
  type: `GET_${resource}_SUCCESS`,
  data,
});

export const getRequestFailure = (resource, error) => ({
  type: `GET_${resource}_FAILURE`,
  error,
});

export const getRequest = (resource, params = {}) => {
  const resourceDisplayString = resource.replace(/\/.*/, '').toUpperCase();

  return (dispatch) => {
    dispatch(getRequestStart(resourceDisplayString));
    return new Promise((resolve, reject) => {
      axios.get(`${API_URL}${resource}`, params).then((response) => {
        dispatch(getRequestSuccess(resourceDisplayString, response.data));
        resolve();
      }).catch((e) => {
        dispatch(getRequestFailure(resourceDisplayString, e));
        reject();
      });
    });
  };
};
Then anywhere in my code I can write

code:
getRequest('foo/', {some data})
And my reducer (foo/reducers/all.js) will handle the changes
code:
const all = (state = [], action) => {
  switch (action.type) {
    case "GET_FOO_SUCCESS":
      return {
        ...state,
        ...action.data,
      };
    default:
      return state;
  }
};

export default all;

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
In Chrome when you choose "Save As" of type "Webpage (Complete)" what determines which files come along for the ride?

Is it only files referenced in the DOM tree or original HTML source or something, but not files referenced by JavaScript?

I'm thinking of the JavaScipt Image() objects I construct, then set their src to a relative URL on my server. Do those not count?

In the "Network" tab of Chrome devtools I can see those files arranged in their proper assets folders just like I want the user to be able to save, but saving the web page doesn't copy the assets (images / sounds / 3D models) locally like I need.

Also is there any way to include more helpful files that I want to provide a user who saves my page for code remixing on their own machine? (Specifically a batch / shell file that lets them easily set up a python local host)

If I can figure this out my students can have a really good workflow to remix parts of my tutorial into their homework assignment. They'd use Chrome's local Workspaces feature to type their code edits directly into the Chrome debugger area and save them to their own files.

Happy Thread fucked around with this message at 04:22 on Jun 6, 2018

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Looks like it's smart enough to only include stuff that makes it into the DOM.

If you're not going to throw it on Github and tell them to fork it if they feel like it, just include a link to a zip file. Since you mentioned Python, it's pretty easy to make a script that generates one on the fly based on whatever you have deployed, or your students have changed to make it easier on them to share stuff.

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer
I want to do something incredibly simple and commonplace, but I can't find an answer for it. I want to animate (fade-in and up) when an element would scroll into view. I can't find a vanilla JS or even jQuery answer for this, but maybe I'm trying to reinvent the wheel here? Is there a script anyone can recommend to do this fancy animate when scroll into view stuff with minimal bloat?

The Merkinman
Apr 22, 2007

I sell only quality merkins. What is a merkin you ask? Why, it's a wig for your genitals!

LifeLynx posted:

I want to do something incredibly simple and commonplace, but I can't find an answer for it. I want to animate (fade-in and up) when an element would scroll into view. I can't find a vanilla JS or even jQuery answer for this, but maybe I'm trying to reinvent the wheel here? Is there a script anyone can recommend to do this fancy animate when scroll into view stuff with minimal bloat?
I'd really just use JavaScript (here is a jquery version, or a javascript version) to add a CSS class. Then use CSS transistions to fade-in up.
Something like
code:
.animatingElement{
opacity:0;
transform:translateY(3rem);
transition:opacity .5s, transform .5s;
}
.animatingElement.show{
opacity:1;
transform:translateY(0);
}

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

LifeLynx posted:

I want to do something incredibly simple and commonplace, but I can't find an answer for it. I want to animate (fade-in and up) when an element would scroll into view. I can't find a vanilla JS or even jQuery answer for this, but maybe I'm trying to reinvent the wheel here? Is there a script anyone can recommend to do this fancy animate when scroll into view stuff with minimal bloat?
You can do this sort of thing with nothing but CSS these days, it's pretty impressive.
https://www.w3schools.com/css/css3_animations.asp

Roadie
Jun 30, 2013

huhu posted:

Would love some feedback on this code I wrote for my redux store and to see if there are any pitfalls or ways to improve on it. For each site I make I've always felt like communicating with the API was a bit sloppy so I tried to write a better request function that handles the actions and actions creators and then the rest of the store is only responsible for creating reducers for the requested data.

Use redux-pack and redux-actions to replace all that boilerplate.

JavaScript code:
import axios from 'axios';

import { API_URL } from '../../../../constants';

export const getRequest = (resource, params = {}) => ({
  type: `GET_${resource.replace(/\/.*/, '').toUpperCase()}`,
  promise: axios.get(`${API_URL}${resource}`, params),
  meta: {
    onFailure: console.error
  },
})
JavaScript code:
import { handleActions } from 'redux-actions';
import { handle } from 'redux-pack';

const all = handleActions({
  GET_FOO: (state, action) => handle(state, action, {
    success: prevState => ({ ...prevState, ...action.data })
  })
}, []);

export default all;

Roadie fucked around with this message at 05:00 on Jun 7, 2018

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!
Is there a WebRTC guide suitable for games somewhere (ie. I don't need to know about streaming video or media bits, I just want peer-to-peer data channels as simply as possible without having to use any particular framework; a small standalone library is fine).

I recognize that I have to do something server side, which seems to be just "transmit a single JSON object from the WebRTC host to the WebRTC client" if I understand things correctly(?). And it also seems to be recommended to run a STUN and/or TURN server to avoid an external dependency on those things, maybe?

And I recognize that it's going to be horrible, because network communication is always horrible. It's just this initial connection-forming bit that is unfamiliar and all the "simple instructions" I find go immediately to "here's how to stream a video" and then "now you're done, yay!" which is not really very similar to what I want.

I'm sure I could figure it out from the API documentation but it seems likely there's something better out there and I'm just missing it in my searches, like I was missing parceljs.

Small White Dragon
Nov 23, 2007

No relation.
So, uh, my JavaScript skills are pretty dusty and I want to update them. What frameworks are "in" these days?

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop

Small White Dragon posted:

So, uh, my JavaScript skills are pretty dusty and I want to update them. What frameworks are "in" these days?

Personally I like "none." I've learned an amazing amount of powerful things es6 language features can do by rolling big complex things from scratch with no libraries and iteratively finding cleaner ways to do the same thing. I've read some articles that this is actually coming back in style among JavaScript coders.

Thermopyle
Jul 1, 2003

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

ES6 is a very small language, there's no need to eschew libraries to learn it.

JS is bad because there's basically no standard library and it's silly to reimplement a bunch of stuff that's been implemented elsewhere.

I mean, if you're just having fun or trying to learn how something works, sure. But if the point of your project is to build a thing...

As far as what libraries it depends on what you're building.

Roadie
Jun 30, 2013

Small White Dragon posted:

So, uh, my JavaScript skills are pretty dusty and I want to update them. What frameworks are "in" these days?

React, Redux, ApolloJS.

TheFluff
Dec 13, 2006

FRIENDS, LISTEN TO ME
I AM A SEAGULL
OF WEALTH AND TASTE
Also, use lodash. It’s not as critical anymore with ES6 but there’s still a bunch of common things that still aren’t available natively.

Also also, use typescript. At first you might think “ugh, transpiling” but in the end it just makes everything far less painful.

mila kunis
Jun 10, 2011
I like ramda a lot more than lodash.

TheFluff
Dec 13, 2006

FRIENDS, LISTEN TO ME
I AM A SEAGULL
OF WEALTH AND TASTE

tekz posted:

I like ramda a lot more than lodash.

Functional is cool and good and I use lodash-fp myself, but for someone who isn't familiar, going all out from the start might be a bit overwhelming. Took me a while to get used to lodash-fp. Might try ramda next project though.

TheFluff fucked around with this message at 22:03 on Jun 12, 2018

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

tekz posted:

I like ramda a lot more than lodash.


TheFluff posted:

Functional is cool and good and I use lodash-fp myself, but for someone who isn't familiar, going all out from the start might be a bit overwhelming. Took me a while to get used to lodash-fp. Might try ramda next project though.

Are there any performance concerns with using ramda or lodash-fp?

MrMoo
Sep 14, 2000

I found this today and had to nudge it a bit because I was compiling to ES2015 and it was breaking. A Promise wrapper that performs retries inside another Promise.
JavaScript code:
function wait(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
}
function retry(fn, delay, retry_count) {
        return new Promise((resolve, reject) => {
                return fn()
                .then(response => {
                        resolve(response);
                })      
                .catch(reason => {
                        if (retry_count) {
                                return wait(delay)
                                .then(retry.bind(null, fn, delay, retry_count - 1))
                                .then(resolve)
                                .catch(reject);
                        }               
                        return reject(reason);
                });     
        });             
}    
Looks pretty much the same as the one from Yair Kukielka.

Use it something like this:
JavaScript code:
retry(() => fetch(url, {
        method: "GET",
        headers: {
                "Accept": "application/json",
        },
        mode: "cors",
        credentials: "include",
        cache: "no-cache",
        redirect: "follow",
}), CMS_TIMEOUT * 1000, CURL_RETRIES)
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.error(error));

Adbot
ADBOT LOVES YOU

Roadie
Jun 30, 2013
Use p-retry instead. It has better coverage for various edge cases including being able to abort the retries from the outside.

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