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

gbut posted:

This thread is making me consider writing a floppy drive rattle node package.

Make a music player.

Adbot
ADBOT LOVES YOU

feedmegin
Jul 30, 2008

gbut posted:

In the olden times, all IBM Compatibles (TM) came with a built in beeper (a piezzo speaker usually) that would beep the boot error codes and such. If you had a sound card, and maybe a CD rom drive, it would have been a Multimedia PC (TM) but those were expensive and rare early on.

There's a package for doing beeps, but I doubt anyone bothers maintaining something that would allow you to send custom signals via node.
https://www.npmjs.com/package/node-beep

E: the speaker was not necesarily limited to PC compats. Even earlier systems used ASCII "bell" (code 7 I posted above) that would produce audible "warning". On macs it was replaced by that default "boink" sound coming from the sound card. I haven't touched PC hardware internals in a decade or so, but I believe motherboards should come with a tiny piezzo speaker for the boot issue signaling, as it would be useful when stuff goes sideways.

'Early on'? dude multimedia PCs came out in the mid 90s when I was in my late teens. Actual 'Early on' in the PC world is like 1982. The motherboard doesn't 'come with' the speaker (iirc it actually usually comes with the case if there is one, but you can buy them online for not very much and plug them into the motherboard header if not). And yes, I did that, because it's nice to have beep codes if something goes wrong and also really why not.

Seriously, you JavaScript guys are making some of us feel :corsair: as gently caress. I envision a thread full of early 20s hipsters with beards and berets and turtlenecks or something reminiscing about the far off days of their childhood in like 2012 ;p

feedmegin fucked around with this message at 18:58 on Aug 9, 2021

Impotence
Nov 8, 2010
Lipstick Apathy

feedmegin posted:

early 20s hipsters with beards and berets and turtlenecks or something

This was Ruby on Rails.

Data Graham
Dec 28, 2009

📈📊🍪😋



Beardy white guys with Sokka topknots as far as the eye could see

gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


feedmegin posted:

'Early on'? dude multimedia PCs came out in the mid 90s when I was in my late teens. Actual 'Early on' in the PC world is like 1982. The motherboard doesn't 'come with' the speaker (iirc it actually usually comes with the case if there is one, but you can buy them online for not very much and plug them into the motherboard header if not). And yes, I did that, because it's nice to have beep codes if something goes wrong and also really why not.

Seriously, you JavaScript guys are making some of us feel :corsair: as gently caress. I envision a thread full of early 20s hipsters with beards and berets and turtlenecks or something reminiscing about the far off days of their childhood in like 2012 ;p

You're underestimating my age, dear fellow old. I've been there, in the trenches of 8 bits. I've seen ZX Spectum beams glitter near the NAND gate. Time to die?

Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!
Random observation... Looking for suggestions for varying things can get a bit frustrating at times. I was looking for a charting module that outputs SVG instead of using canvas, googling around for it I ran into several posts, virtually all of them linking commercial projects for the most part. Most suggestions seemed unsatisfactory. So just now I was looking at the web dashboard of my 3D printer, it had a chart. Turned out to be SVG. I looked what it was, turns out to be ECharts from Apache, which looks like a pretty powerful library. Is there a catch, or why didn't it come up in my searches?

--edit:
Scrolling through the examples page, I'm even more confused. Back when I looked for a library, chart.js came up first, then things like amCharts, Flexcharts, ApexCharts and god knows what sort of alphabet soup, but this one flew under my radar. Huge variety of charts, easy to use, and SVG which makes printing easier than this DPI fuckery with chart.js.

Combat Pretzel fucked around with this message at 18:49 on Aug 12, 2021

Impotence
Nov 8, 2010
Lipstick Apathy
echarts is great. i use it heavily.

it fairly recently was given to the apache foundation - maybe a year or so? before that it was 100% chinese. no english docs. no english issues, no english support, and most companies blocked all of echarts' sites and examples as they were hosted on bare chinese IPs (this is because you have to apply for a licence for any website you host in china, so people frequently just http 210.219.whatever:8123)

there are a bunch of other projects that are similar to this, like vuejs's most used ui framework, element-ui. massive adoption but you would not find it unless you went hunting for it in the english speaking world.

baidu, alibaba, tencent use it, and they're basically bigger than most american tech companies in terms of raw user size. it handles millions of data points well when rendering in webgl (svg dies because it has to manage a billion DOM elements)

Impotence fucked around with this message at 22:45 on Aug 12, 2021

Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!
Is there any sort of callback or whatever when React removes elements from the DOM?

Right now I'm trying to find a way to wrangle ECharts into printing, and I'm currently attempting this with wrapping a chart with a helper, kind of so:

code:
<EChartsPrintHelper>
    <ReactEChart ... />
</EChartsPrintHelper>
Said helper class would then add listeners to beforeprint and afterprint. It would save the container client sizes, call resize() on the EChart to make it fit certain dimensions, and when printing is done, it'd resize to the stored values.

But once an user navigates away, so would EChartsPrintHelper, except it'll leave the listeners still in place, and thus cause drama and also not get garbage collected?

--edit:
Found it I think. componentWillUnmount().

Combat Pretzel fucked around with this message at 18:30 on Aug 22, 2021

necrotic
Aug 2, 2005
I owe my brother big time for this!
For functional components it’s done through useEffect: any function returned from it is called when the component is unmounted.

huhu
Feb 24, 2006
Edit: nevermind.

huhu fucked around with this message at 20:57 on Aug 22, 2021

Data Graham
Dec 28, 2009

📈📊🍪😋



huhu posted:

Edit: nevermind.

I feel like this is as good a thread title as any

Doh004
Apr 22, 2007

Mmmmm Donuts...
I'm starting to dig deeper into the NodeJS ecosystem after having been away from it for about 3 years and being primarily a Rails developer. Are there any good ORMs that I can trust? Prisma?

What about job queues? I've found Bull/Kue/Bee-queue so far and they seem good?

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer
Sequelize is by far the most popular ORM, but I'd advise against using it, and instead use a nice query builder like knex so you have control and don't need to learn yet another ORM plus its pitfalls.

Munkeymon
Aug 14, 2003

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



I'm using the official Firebase library in a Node service and it doesn't like to be initialized more than once (it'll throw) so I did the thing I'd normally do

code:
let firebaseInstance = null;

export default function getFirebase(){
   if (firebaseInstance == null {
      //initialize it
   }
   return firebaseInstacne;
}
Someone on the team is pretty sure just exporting the instance as the default will cache it for the service lifetime but I'd like to be more than pretty sure. Anyone know if it's guaranteed to be cached?

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

Munkeymon posted:

I'm using the official Firebase library in a Node service and it doesn't like to be initialized more than once (it'll throw) so I did the thing I'd normally do

code:
let firebaseInstance = null;

export default function getFirebase(){
   if (firebaseInstance == null {
      //initialize it
   }
   return firebaseInstacne;
}
Someone on the team is pretty sure just exporting the instance as the default will cache it for the service lifetime but I'd like to be more than pretty sure. Anyone know if it's guaranteed to be cached?

Yes. We use this approach for a few client libraries.

Roadie
Jun 30, 2013
If it's one of those things where it connects as needed rather than needing a persistent connection throughout (so you don't have to worry about race conditions), you can also just do:

JavaScript code:
// firebase.js
import { Whatever } from 'firebase'

export default new Whatever()
JavaScript code:
// otherthing.js
import firebase from './firebase'

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer
I've been teaching myself Next + Sanity.io, and I'm stuck in a similar place I was last time I tried to work with a data set. I can display data from arrays fine with a map, but array-like objects give me problems. Here's my code:

code:
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import { useState, useEffect } from 'react'

export default function Home() {

const SanityTest = () => {

  const sanityClient = require('@sanity/client')

  const [movieData, setMovieData] = useState([])

  let movieOutput

  const client = sanityClient({
    projectId: 'tjsn9l2c',
    dataset: 'production',
    apiVersion: '2019-01-29', // use current UTC date - see "specifying API version"!
    //token: 'sanity-auth-token', // or leave blank for unauthenticated usage
    //useCdn: true, // `false` if you want to ensure fresh data
  })

  useEffect(() => {

    const query = '*[_type == "movie"]'

    client.fetch(query).then((data) => {
      setMovieData([data])
    })

    console.log('test')

  }, [client, movieData])

if (movieData.length > 0) {
  
  return(
    <div>

    <p>
      {JSON.stringify(movieData)}
    </p>
    </div>

  )

  } else {
    return (
      <div>Loading...</div>
    )
  }

}

  return (
    <div className="container">
      <Head>
        <title>Sanity Test</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <SanityTest />
      </main>
    </div>
  )
}
This is the default Sanity installation from the command line with sample sci-fi movie data. I'd think I'd be able to just do something like:

code:
{movieData.map((item, i) => {
  <span key={i}>{item.title}</span>
}
...but when I try anything like that it tells me it found an object with keys instead of an array.

worms butthole guy
Jan 29, 2021

by Fluffdaddy
I use WordPress and wp graph ql for a cms

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer

LifeLynx posted:

I've been teaching myself Next + Sanity.io, and I'm stuck in a similar place I was last time I tried to work with a data set.

code:
{movieData.map((item, i) => {
  <span key={i}>{item.title}</span>
}
...but when I try anything like that it tells me it found an object with keys instead of an array.

I don't know next or sanity, but this code block is missing a return statement, or should not have curly braces around the span.

Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!
Regarding the useState hook inside a React functional component, are the state variables globally unique (like you can't use a functional component more than once, otherwise your state gets hosed up), or does it work like classes anyway?

necrotic
Aug 2, 2005
I owe my brother big time for this!
You can use them as many times as you want, same as classes; the state is local to each mounted instance.

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer

Fixins posted:

I use WordPress and wp graph ql for a cms

I've used Wordpress for many years, and it's so clunky for what I want to do. I like the idea of having the whole thing in Javascript instead of Javascript with a PHP backend. I want to treat things as items with defined schema, not a blog post with Advanced Custom Fields tacked on.

Osmosisch posted:

I don't know next or sanity, but this code block is missing a return statement, or should not have curly braces around the span.

Ah you're right. I just don't know what to do when I get that "Object is not a valid React child" error or whatever it is. When I do a JSON.stringify, it looks like any other array, so just treat it as an array!

Roadie
Jun 30, 2013

LifeLynx posted:

Ah you're right. I just don't know what to do when I get that "Object is not a valid React child" error or whatever it is. When I do a JSON.stringify, it looks like any other array, so just treat it as an array!

What "that error" do you mean? Supply more context with the actual code you're using.

barkbell
Apr 14, 2006

woof
whats your array-like object look like

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer
This works, but I'm probably Doing Things Wrong. I know because I accidentally made 156,600 API requests from using useEffect incorrectly. I'm going to go back to the basics on some online classes, because trying to learn-by-doing turned out to be a bumpy ride.

code:
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import { useState, useEffect } from 'react'


export default function Home() {

const [movieData, setMovieData] = useState([])

const SanityTest = () => {

  const getData = () => {

    const sanityClient = require('@sanity/client')

    const client = sanityClient({
      projectId: 'tjsn9l2c',
      dataset: 'production',
      apiVersion: '2019-01-29', // use current UTC date - see "specifying API version"!
      //token: 'sanity-auth-token', // or leave blank for unauthenticated usage
      //useCdn: true, // `false` if you want to ensure fresh data
    })

    const query = '*[_type == "movie"]'

    client.fetch(query).then((data) => {
      setMovieData(data)
    })
  }

  useEffect(() => {
    if (movieData.length < 1) {
      getData()
    }
  }, [])

  if (movieData.length > 0) {
  
  return(
    <div>

    {Object.keys(movieData).map((key, i) => {
      return(<p key={i}>{Object.values(movieData)[key].title}</p>)
    })}

    </div>

  )

  } else {
    return (
      <div>Loading...</div>
    )
  }

}

  return (
    <div className="container">
      <Head>
        <title>Sanity Test</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <SanityTest />
      </main>
    </div>
  )
}

barkbell
Apr 14, 2006

woof
youre going to want to do your data fetching from your cms in getStaticProps

check out this link: https://nextjs.org/docs/basic-features/data-fetching

here is an example of nextjs using sanity: https://github.com/vercel/next.js/blob/canary/examples/cms-sanity/pages/posts/%5Bslug%5D.js

the idea is that updating your cms will trigger a rebuild of the site and populate the data at build time

this works for a cms that you can control, but if you want to fetch data at runtime when the user visits the webpage, take a look at these examples https://www.freecodecamp.org/news/fetch-data-react/

how your code is formatted is a bit weird, you are importing the sanity client within the getdata function when it should probably be defined at the top, its kinda hard to follow i think youve made this more complicated than need be

i hope that helps

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer

barkbell posted:

youre going to want to do your data fetching from your cms in getStaticProps

check out this link: https://nextjs.org/docs/basic-features/data-fetching

here is an example of nextjs using sanity: https://github.com/vercel/next.js/blob/canary/examples/cms-sanity/pages/posts/%5Bslug%5D.js

the idea is that updating your cms will trigger a rebuild of the site and populate the data at build time

this works for a cms that you can control, but if you want to fetch data at runtime when the user visits the webpage, take a look at these examples https://www.freecodecamp.org/news/fetch-data-react/

how your code is formatted is a bit weird, you are importing the sanity client within the getdata function when it should probably be defined at the top, its kinda hard to follow i think youve made this more complicated than need be

i hope that helps

I definitely have made it more complicated and it definitely helps, thank you! I took a working example and reverse engineered it into something much worse.

Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!
I'm slowly converting my React class components to functional ones, among other reasons because various theming solutions are tons easier to work with hooks and poo poo. And React announcing somewhen in the past that they're focusing on hooks and putting classes on maintenance. But classes made it easier to maintain internal state. In functional components I resorted to a state variable hosting an object for this, that I modify directly. Is that OK, or is this going to blow up into my face in some fashion? It's not related to rendering JSX.

gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


I'm not sure I follow. The useState hook, or just a variable declared in the component body? The latter will get lost on component rerender.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
If you need something akin to an instance variable, you can use the useRef hook and store whatever you want in there. Updates to a ref do not trigger a render. But as was just said, useState is for holding components state.

Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!
Hmm, thanks, I'm gonna look into it.

What I was doing so far was creating a state variable called rt (for runtime, because ???) and doing rt.var = ... instead of the this.var = ... previously in a class. Seemed to work fine. So far anyway.

gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


This is probably working because you're changing a property of the referenced object. I'm not sure about the exact useState mechanism, but:
- it probably circumvents the "needs to rerender" signal because you're not using the setter
- in case the useState doesn't reuse the same object, you lose all the changes when the component (or any ancestor) rerenders.

Ima Computer
Oct 28, 2007

Stop all the downloading!

Help computer.

Combat Pretzel posted:

What I was doing so far was creating a state variable called rt (for runtime, because ???) and doing rt.var = ... instead of the this.var = ... previously in a class. Seemed to work fine. So far anyway.

Storing values as instance properties on a class component (this.var = ...) is something you should only be doing if you explicitly do not want changes to that value to trigger your component to re-render. If this is really what you need, you should be using useRef() in your functional component to create a persistent reference to an object where you can store those values.

This really isn't a very common use case to run into though. In the majority of cases, you do want state changes to trigger re-renders.

In class components, this is done by calling the .setState() method of the component instance.

For functional components (the best components) you should be using the useState hook and using the setter function it returns to update your state value(s).

I would recommend reading the documentation for react hooks before proceeding further with converting your components.

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer
I figured out Formik and it's really cool. Combined with Yup it's really easy to do validation and style it. Also gave me more practice on hooks and passing props around, as a bonus. The only trouble is - now how do I send emails? And how do I control how the email looks when it's sent? The company I do my Wordpress sites for uses Mandrill (now called Mailchimp Transactional Email, I think), so I tried signing up for that, but it requires a real domain name and paid services to send through an API.

What's the most pain-free way to do this, and to try something for free before I purchase a domain name? The app is hosted on Vercel, and if I could send some trial emails from the form to my personal email without spending a dime on a domain name or a mail server plan that'd be ideal.

Edit: Looks like Netlify does all this built-in, which is nice. I bought a $3 domain name to be able to test DNS stuff and now I don't immediately have to worry about anything but coding the interface.

LifeLynx fucked around with this message at 01:08 on Sep 11, 2021

Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!
Help me understand the default theme of Material UI. Is it intentional that none of the components have any padding/margin/spacing by default?

Say if I create a Paper element with three buttons inside, it's all caked together without any whitespace at all. I'm using createTheme, ThemeProvider and even CssBaseline. From what I can tell, it's applying the default theme, because colors change if I say modify it in createTheme.

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer

Combat Pretzel posted:

Help me understand the default theme of Material UI. Is it intentional that none of the components have any padding/margin/spacing by default?

Say if I create a Paper element with three buttons inside, it's all caked together without any whitespace at all. I'm using createTheme, ThemeProvider and even CssBaseline. From what I can tell, it's applying the default theme, because colors change if I say modify it in createTheme.

You can specify your layout and any padding/spacing with Grid components.

If that's overkill, take a look at the spacing properties: https://material-ui.com/system/spacing/

Haystack
Jan 23, 2005





So I'm looking for a resource to help my wife get up to speed with browser javascript. Just a basic, solid introduction to ES6. She learns best by tinkering, so I'm thinking something that has a lot of interactive code and example projects to mess with. She's got a fair amount of experience with PHP so it doesn't have to be bare basics. Any suggestions?

Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!

Osmosisch posted:

You can specify your layout and any padding/spacing with Grid components.

If that's overkill, take a look at the spacing properties: https://material-ui.com/system/spacing/
Yeah, I know about these things. I just find it odd that if I put say two buttons (OK and Cancel) next to each other in the same grid cell, that there's no spacing whatsoever, unless I actually define it myself. Same goes for the Paper component, which you'd think as a wrapper, it'd come with some default padding. The CSS baseline stuff says it has defaults for starting out, but I guess that doesn't include any spacing. (Using the grid for button layout seems wrong, because they're all over the place depending on window width.)

I'm just asking to verify whether I'm doing something wrong, anyway, so that I don't start to modify the theme for no reason.

--edit:
So essentially what I'm going on about is that there's this:

https://material.io/design/layout/responsive-layout-grid.html#columns-gutters-and-margins

...and I had the assumption that these things are done by default out of the box.

Combat Pretzel fucked around with this message at 20:17 on Sep 16, 2021

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

Combat Pretzel posted:

Yeah, I know about these things. I just find it odd that if I put say two buttons (OK and Cancel) next to each other in the same grid cell, that there's no spacing whatsoever, unless I actually define it myself. Same goes for the Paper component, which you'd think as a wrapper, it'd come with some default padding. The CSS baseline stuff says it has defaults for starting out, but I guess that doesn't include any spacing. (Using the grid for button layout seems wrong, because they're all over the place depending on window width.)

I'm just asking to verify whether I'm doing something wrong, anyway, so that I don't start to modify the theme for no reason.

--edit:
So essentially what I'm going on about is that there's this:

https://material.io/design/layout/responsive-layout-grid.html#columns-gutters-and-margins

...and I had the assumption that these things are done by default out of the box.

You can use a Stack with spacing to space them out. The first buttons demo uses this approach.

https://codesandbox.io/s/basicbuttons-material-demo-forked-3zeup?file=/demo.js

Change the spacing param to 0 and observe they are right next to each other.

I'm pretty sure in MUI the _components_ have no spacing by default, and you _must_ use one of the containers or provide your own spacing rules. Components are things with a look, containers are used to align/space out those components.

Adbot
ADBOT LOVES YOU

Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!
Thanks for pointing out Stack. But you show, too, that there are no defaults on containers either. I'd have figured that it had some out of the box, given the guidelines I linked to.

That said, after some digging around (more like flailing), it seems I can set that poo poo globally via createTheme. Which is good I guess, because I'd like to avoid setting everything manually:
code:
const theme = createTheme({
    components: {
      MuiStack: {
        defaultProps: {
          spacing: 1
        }
    }
    // That and other components
});
Thanks.

Combat Pretzel fucked around with this message at 21:13 on Sep 16, 2021

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