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
camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

Newf posted:

Further playing with js / web / node technologies, and I'm trying to author a command-line program installable via npm. With the following package.json,

JavaScript code:

{
  "name": "lynda-copy-course",
  "version": "1.0.0",
  "description": "A utility for copying downloaded Lynda.com courses from one machine to another",
  "bin": {
    "lynda-copy-course": "./src/index.js"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "./dist/lynda-copy-course"
  },
  "license": "MIT",
  "dependencies": {
    "ncp": "^2.0.0",
    "sqlite3": "^3.1.8"
  }
}

I'm running (from the root of the project) "npm install . -g". This works in so far as it makes lynda-copy-course available on my command line. The problem is that when I run this new addition to my path, visual studio opens up the index.js file - node doesn't run it.

I've been poking at some package.json files from different cli packages, but I can't find what I'm missing here. Any suggestions? You can look at the whole shebang at github.com/nilock/lynda-copy-course.

"Please make sure that your file(s) referenced in bin starts with #!/usr/bin/env node, otherwise the scripts are started without the node executable!"

From the npm docs

Adbot
ADBOT LOVES YOU

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
I’ve done a few TDD trainings and always come away thinking “wow that was cool, but there’s no way it scales well or works well with async calls”. I would love to be proven wrong, though.

I’ve never done a training that used JS, so maybe that’s part of the issue.

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
That's not odd, that makes sense since edges is an array of nodes. Node isn't an accessible key from the array itself. You'd need to do like products.edges[0].node.title

Also since edges is an array you can do .map or .forEach or whatever to access each node

e:
I dunno poo poo about Svelte and I'm having trouble following what exactly your issue is, but this should work better than 4 loops or whatever:

code:
import { getProducts } from '../../store';

export async function load(ctx) {
    let products = await getProducts();
    return { props: { products } };
}

<div class="mainContent">
	<div class="contentBlock">
		<div class="RULES">
			<img src="/image0.jpeg" alt="Hentai Free since 20201" />
		</div>
		<div class="gameShelf">
			{#each products.edges as edge}
				{console.log(edge.node)}
			{/each}
		</div>
	</div>
</div>

camoseven fucked around with this message at 20:38 on Oct 21, 2021

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
I probably missed passing the props to the html since I don't know svelte, so make sure you do that

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
I hadn't heard of that, but a quick search on it and I'm :swoon:

Is this supposed to be able to replace Moment.js? Because I would loving love to replace Moment.js

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
I think we can all agree that typescript kicks rear end, at least

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

LifeLynx posted:

I think I understand vanilla JS, React, and NextJS enough to attempt Typescript. Should I convert a project or is it better to start fresh? Looking over the typescriptlang.org site I'm not sure what it does for me that ESLint doesn't already (for a small NextJS site at least), but I need to see what the fuss is all about.

Have you gone through this: https://www.typescriptlang.org/docs/handbook/intro.html ? It's pretty good.

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

Summit posted:

All code is terrible and needs careful management and validation to not explode at the worst possible moment.

Actually my code is perfect every time

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

It's weird to be on the same team as Microsoft, but drat this proposal kicks rear end

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

LongSack posted:

I am in the middle of rewriting one of my Blazor server front ends into React. I don't think this is a React question, but more JavaScript related, so here goes.

I am making a retail store page as a demo (it also has an employee portal and vendor portal). On the index page, just for variety, the page selects three products at random and displays them to the user as items specially selected for them.

I have this function:
JavaScript code:
export function getData(url: string) {
  return fetch(url).then((response) => {
    if (!response.ok) {
      throw Error("There was an error fetching data: " + response.statusText);
    }
    return response.json();
  });
}
which works just fine. But rather than call getData all over the place, I'm trying to write services which abstract out the details. To that end, I've written my first service, ProductService which contains this function:
JavaScript code:
import { getData } from "./api";
import { IProduct } from "../Interfaces/IProduct";
import { uriBuilder } from "./tools";

export function RandomProducts(count: number): IProduct[] | null {
  const uri = uriBuilder("Product/Random/" + count);
  getData(uri)
    .then((data) => {
      return data;
    })
    .catch((error) => {
      throw new Error(error);
    });
  return null;
}
When it runs, I can see (via console.log) that data correctly has three products chosen at random. So far, so good.

So I try to call the service in one of my pages, like this:
JavaScript code:
import { useEffect, useState } from "react";
import { IProduct } from "../../Interfaces/IProduct";
import { RandomProducts } from "../../Services/ProductService";
import "./MainPage.css";

export default function MainPage() {
  const [products, setProducts] = useState<IProduct[] | null>(null);
  useEffect(() => {
    const p = RandomProducts(3);
    console.log("p = " + p);
    if (p) {
      setProducts(p);
    } else {
      setProducts(null!);
    }
  }, []);
  return (
    <div className="mainpage">
      <h1 className="mainwelcome">Welcome to the JimCo Retail site</h1>
      <h3 className="mainheader">Items selected for you!</h3>
      {products && <div>Products</div>}
      {!products && <p className="noproducts">No products were found</p>}
    </div>
  );
}
This does NOT work. The console.log shows that p is null (note that the "guts" of the page have not been fleshed out yet).

So I suspect that I have some sort of fundamental disconnect on promises or something. I can't figure out why RandomProducts has three products in an array, and seems to return it, but the caller is getting back null.

Can someone educate me please? TIA

The promise is asynchronous, so basically you are saying "go fetch me three products and let me know when you're done and what they are". But the code doesn't stop and wait for the fetch to happen, it moves right on to the console.log, if block, etc. I assume when you logged out of RandomProducts you were doing it in the "then" block, so it waited til the call was done then logged the data you got back.

Also RandomProducts returns null but it actually needs to return a promise, then you can async/await or chain it or whatever.

Phone posting but hopefully that helps a bit

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

Sab669 posted:

Has anyone encountered this error before?

I'm trying to install this library, I tried both their Recommended Way and got the above error. Then I tried their Angular CLI steps but as soon as I add the imports to my app.module.ts I get the above error.

I've googled around a bunch and I see lots of posts with similar errors but a different export, and all the solutions seem specific to the whatever library that specific post is about.

You need to set your bundler (probably webpack) to interpret .mjs files as js files. Or use an older version of that library that doesn't use .mjs files

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

LongSack posted:

I ripped out all the array stuff when I gave up and went with individual strings, but I'll try to reconstruct it here:
TypeScript code:
const [messages, setMessages] = useState<string[]>([]);
const [modalHeading, setModalHeading] = useState<string>('');
...
function addMessage(msg: string) {
  const m = messages || [];
  m.push(msg);
  setMessages([...m]); // I also tried setMessages(m); and setMessages([...messages, msg]);
}

}

Did you try using something like _.cloneDeep? I have had issues where setting a variable equal to the state array just creates a reference to the state array, so when you manipulate what you think is the copy you're actually manipulating the original and can get all kinds of weird bugs. CloneDeep (and related solutions) create a brand new array in memory, which React likes much better.

e: so like:

code:
const m = messages ? _.cloneDeep(messages) : [];

OR 

const m = messages ? [...messages] : []; // NOTE: only works if the data is not nested!!

camoseven fucked around with this message at 14:45 on May 13, 2022

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

Janitor Ludwich IV posted:

Hi friends,

I'm working heavily with stuff in google sheets and I have been playing around with GAS (google apps script). I know this is based on javascript. I'm wondering if it's worth learning GAS specifically or if I should just learn the latest and greatest edition of javascript?

I hadn't heard of GAS, but it looks like it IS JavaScript. Not sure you could learn GAS separate from JS

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

Janitor Ludwich IV posted:

I think that answers my question then! From what I read is GAS may be missing some newer syntax as it's mostly built on 1.6 / 1.7. it will also have a lot of Google specific functions.

But I think if I get to know how to do JS logic, loops, declarations I will be in good stead for understanding Google's documentation.

There is definitely a lot newer books for JavaScript but I did find a couple for GAS

https://developers.google.com/apps-script/guides/v8-runtime

It looks like GAS uses V8 by default now, so you can use all the latest features of JS. Like you said there will be functions and stuff specific to the GAS environment, but you would be well served by doing a crash course in JS

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
I'm really confused about what y'all are trying to do. Just using TS and setting things to a type will do all the type checking for you at compile time. Why are you trying to add if statements to do what TS already gives you out of the box?

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
In nearly 7 years of professional JavaScripting I have never written a class

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

echinopsis posted:

next step is figuring out date()

If you need to do anything complicated I highly recommend using a library instead of trying to deal with the native Date interface directly. We use Day.js at work but there's a bunch of options

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

Video Nasty posted:

Moment.js is my go-to library when dealing with date\time objects if I can use it (sometimes I can't :gonk: )

I'm sorry you had to find out this way but here's a note from the Moment devs:

Moment.js is a legacy project, now in maintenance mode. In most cases, you should choose a different library.

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

echinopsis posted:

poo poo this is driving me crazy.

is it normal that everything assumes you're running node?

at least the dayjs was straightforward, it worked well until I couldn't figure out how to include plugins

anyway, it's a slow road trying to get something as basic as datetime working it seems.

You usually want to use import for front end apps, though you can load scripts directly as indicated by the DayJS docs.

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

echinopsis posted:

I'm trying that final method, and the tricky part seems to be the dayjs.extend();

I don't seem to be able to paste source stuff into this but basically I
script src https://unpkg.com/dayjs@1.11.3/dayjs.min.js
script src https://unpkg.com/dayjs@1.11.3/plugins/relativetime.min.js

and then dayjs.extend(relativetime)

now that plain didn't work, so I tried extend(window.relativetime)

and that seems to work.. except it seems to be finding a problem
code:
Uncaught TypeError: Cannot read properties of undefined (reading '$i')
    at w.extend (dayjs.min.js:1:6457)
    at index.html:25:13
which kind of seems like it's saying the scripts I am referencing have errors. although I am sure it's something I am doing wrong.

Capitalization matters for the extend, it's relativeTime

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

worms butthole guy posted:

Hey goons simple question. It's been a while since I messed around with NodeJS and PUG.

How do I wait for a DB call using mongoose and then render the page? I'm trying to experiment with OAuth and I need to make a call to get user Information and I want to display it to test it. Here is what I have:

code:


// Lookup DB
const LookUpDB =  async (accountID) => {
  Account.findOne({accountId : accountID}, (e, account)=>{
      if (e){
        console.log(e);
      }

      console.log('Account info: ' + account);

      return account;
  });
}

/* GET home page. */
router.get('/', async function(req, res, next) {

  try{
    const accountInfo = await LookUpDB(1);

    res.render('index', { title: 'Foxtrot Tango', loggedIn, accountInfo });
  }
  catch(e){
    next(e);
  }

});
The console log in LookUpDB works, but Pug thinks there's nothing in accountInfo when I console log it. I'm guessing it has to do with Async and Await?

Thanks goons

Right now that `return account` is returning the value to the outer function (LookUpDB), but LookUpDB is not returning anything so when you invoke it you just get undefined. findOne is already an async function, so you don't need to wrap it like you're doing.

edit: i should say I'm pretty sure it's already async. I don't use mongoose but that's what skimming the docs leads me to believe

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
No problem. I will say that your abbreviation of "error" to "e" is triggering me lol. In my experience "e" is used in event handlers as the event object, whereas an error check would refer to "err" or "error"

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
I'm enjoying following your progress and am looking forward to Committing some Crimes

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

Nolgthorn posted:

In fact lets just make typescript the official language, starting tomorrow everything written in javascript no longer works. Job done.

I second this motion

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
Works on my machine :shrug:

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

Jabor posted:

It's actually the opposite - the larger the project, the more you need to know the component library being used, and the less you need to care about minutiae of HTML and CSS.

Once you get large teams of people all working on the same project, you literally have to componentize - if you want to be at all productive, you can't have people loving around with CSS and inadvertently changing parts that aren't the thing they're directly working on. Once you have a componentized UI, only the developers actually creating the components need to care about HTML and CSS - everyone else can use the components as-is and can put all their effort into caring about how those components are composed together and wired up to the data you're wanting to display in them.

This is certainly how upper management imagines that it should work. But it sure does not!

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
Honestly a SPA that doesn't hook up to any databases or APIs and just makes pretty graphs based on sliders is dead simple if you know what you're doing, and you should probably hire a contractor to do it in a week instead of spending time trying to figure it out yourself

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
I hate web components so much. It's possible there's a good way to use them, but every implementation I've been forced to work with has been an absolute mess

Adbot
ADBOT LOVES YOU

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
Big Day.js fan here

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