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
ynohtna
Feb 16, 2007

backwoods compatible
Illegal Hen
From a quick scan, I think your equals function needs to compare both .v and .a members of your set's objects to ascertain value equivalence.

Beyond that, have you tried sticking a breakpoint on https://github.com/montagejs/collections/blob/master/sorted-set.js#L77 and inspecting the two values that are causing the error to be thrown?

Adbot
ADBOT LOVES YOU

5TonsOfFlax
Aug 31, 2001
Never used that library before, but It looks like your equality function examines only 'a' and all of those are different, so nothing's equal. But you have two objects with v:1, so those are also coming up as neither greater than the other. That's probably what's confusing it. As ynohtna says, adjust your functions so that anything that's not equal is also guaranteed a (stable) ordering.

Sedro
Dec 31, 2008

I'm Crap posted:

Has anyone here ever used Collections.js, and can you explain why it's shrieking at me? I specifically gave it an equals function and a comparator function, so I don't know why it's complaining about things being "incomparable". It works fine if I give it an array of objects with only the 'v' property and "null" as an equals function, or an array where only one object has 'a' set. Maybe I'm overlooking something really stupid.
...
Failing that, does anyone know any JavaScript data structure libraries that are as fully featured as Collections.js, but actually work? Buckets seems okay from what I've seen of it (this example works in Buckets) but its APIs are pretty bare-bones.

According to the API docs, the constructor you use is SortedSet(values, equals, compare). Equals and compare need to agree, so this usage is incorrect (although I'm not sure a collections API has any business throwing an exception):

code:
set = new SortedSet(objs, function(x, y){
  return x.a === y.a;
}, function(x, y){
  return x.v - y.v;
});

// equals({v: 1, a: 'b'}, {v: 1, a: 'f'}) === false // "equals" says they're not equal
// compare({v: 1, a: 'b'}, {v: 1, a: 'f'}) === 0 // "compare" says they're equal
You could define your equals function in terms of your compare function:
JavaScript code:
function compare(x, y) {
  var c = x.a.localeCompare(y.a);
  if (c !== 0) return c;
  return x.v - y.v;
}
function equals(x, y) {
  return compare(x, y) === 0;
}

set = new SortedSet(obs, equals, compare);

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Fruit Smoothies posted:

This is a Vue.js framework question, so I understand this may not be the perfect thread for it. I am having issues with the scoping of slots.
Here's a simple list example. Most Vue tutorials will end up with the HTML on your main page looking like this (pre-render)

code:
	<div>
		<list-component></list-component>
	</div>
Which I absolutely despise because it gives you too little information about the construction of the list! My goal is to create

code:
	<div>
		<list-component>
			<list-item v-for:"item in items">
				{{item.name}}
			</item>
		</list-component>
	</div>
The problem here is the <slot> in list-component's template. This slot (which contains <list-item>) has NO context about the "items" data because the slot is rendered outside the parent's scope. There is documentation on this phenomenon here but it's not especially clear documentation!

Before I give up and conform to the ridiculously vague top example, can anyone offer any help here?

Are you talking about slots or just child components? If list-item is a slot, what is it's rendered template?

Because otherwise the child component should be bound to the parent component.

Xom
Sep 2, 2008

文化英雄
Fan of Britches
Thanks for the answers so far, y'all are really helpful!

jQuery question: Is it possible for there to be a race condition in the following, where myDiv is a jQuery selection?
code:
myDiv.css('font-size', '10px');
return myDiv.innerHeight();
Like maybe the computer is really slow, and there's a lot of text, with some 1MB inline images with height:1em, and it's all flowing around some floating element; will jQuery block until the correct innerHeight is available? (Assume that the images were already fully loaded before our code set the font-size.)

Anybody else excited about Firefox 52 having the async keyword being scheduled for release on Tuesday? I'm rewriting Cardery.js to use it.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Xom posted:

Thanks for the answers so far, y'all are really helpful!

jQuery question: Is it possible for there to be a race condition in the following, where myDiv is a jQuery selection?
code:
myDiv.css('font-size', '10px');
return myDiv.innerHeight();
Like maybe the computer is really slow, and there's a lot of text, with some 1MB inline images with height:1em, and it's all flowing around some floating element; will jQuery block until the correct innerHeight is available? (Assume that the images were already fully loaded before our code set the font-size.)

Anybody else excited about Firefox 52 having the async keyword being scheduled for release on Tuesday? I'm rewriting Cardery.js to use it.
I remember having a similar problem - if you try to access like innerHeight/innerWidth immediately after setting the font size style, you may get the values that don't reflect the font size change. (It doesn't seem to be JQuery specific).

Element innerWidth/innerHeight and Font size don't seem to cause the js to block until the layout reflows (see https://gist.github.com/paulirish/5d52fb081b3570c81e3a for a list of properties that force layout reflows.) Setting the font size will update the layout visually, but since it doesn't force a reflow, if you immediately access innerWidth/innerHeight of something that ought to change as a result of the font size changing, it may not give you the desired value.

What I did to work around this is call getBoundingClientRect() on the element. getBoundingClientRect() is slow, but it will immediately trigger a reflow if called on an element. Note that you don't actually have to use the rect returned from getBoundingClientRect(), you can still just get the innerHeight/innerWidth using JQuery later and it will have the right values if you do this.

Xom
Sep 2, 2008

文化英雄
Fan of Britches
https://jsfiddle.net/hgngLh5y/

Augghghh how do I get the div to be the perfect height i.e. tallest image + scrollbar?

I really don't want to script height updates whenever the window height changes.

Xom
Sep 2, 2008

文化英雄
Fan of Britches
line-height: 0 does it.
I had been thrown off by line-height: 1 not quite working.
(line-height: 1.15 was intended for the rest of the page.)

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Xom posted:

line-height: 0 does it.
I had been thrown off by line-height: 1 not quite working.
(line-height: 1.15 was intended for the rest of the page.)

Here's an even better way to do it: https://jsfiddle.net/hgngLh5y/1/

I'm Crap
Aug 15, 2001
Thanks for the replies, dudes, it makes more sense now. I think I was trying to make the equals function do too much work in terms of preventing items with different values but the same 'a' (or 'name') being added to the set, anyway.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
I am replacing an old jquery widget with a react component. In the old widget file, we exported a few functions that then were imported in other files. For instance:

code:

//widget file

export function doesSomething() {

   myWidget.myWidget('internalSomething');
}

$.widget('mywidget', {
   _create: function () {
      ....
   }
}

And then in other files this is referenced like:

code:
import {doesSomething} from 'myWidgetFile.js';
Now I have a react class made but I have no idea how to create an external function that merely calls or acts upon a single function from within the react class. Any ideas? I need to be able to both export the entire react component (which will be the default export) but then also export a couple functions which either do something or just return a value. I cannot figure out hwo to do this because of context hell.

For instance if I have:

code:
export default Class MyComponent extended  React.Component {
 ....
   returnStuff() {
        return this.state.stuff;
   }
}

export function doesSomething () {

    return this.returnStuff() // this won't work because the this context isn't right?  Would 'return MyComponent.returnStuff();' work?
}
I hope this makes sense.

Knifegrab fucked around with this message at 11:56 on Mar 8, 2017

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Knifegrab posted:

I am replacing an old jquery widget with a react component. In the old widget file, we exported a few functions that then were imported in other files. For instance:

code:

//widget file

export function doesSomething() {

   myWidget.myWidget('internalSomething');
}

$.widget('mywidget', {
   _create: function () {
      ....
   }
}

And then in other files this is referenced like:

code:
import {doesSomething} from 'myWidgetFile.js';
Now I have a react class made but I have no idea how to create an external function that merely calls or acts upon a single function from within the react class. Any ideas? I need to be able to both export the entire react component (which will be the default export) but then also export a couple functions which either do something or just return a value. I cannot figure out hwo to do this because of context hell.

For instance if I have:

code:
export default Class MyComponent extended  React.Component {
 ....
   returnStuff() {
        return this.state.stuff;
   }
}

export function doesSomething () {

    return this.returnStuff() // this won't work because the this context isn't right?  Would 'return MyComponent.returnStuff();' work?
}
I hope this makes sense.

Your doesSomething is outside of the class so this is undefined inside the function. (Unless you use doesSomething.call, or a few other things).

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Wheany posted:

Your doesSomething is outside of the class so this is undefined inside the function. (Unless you use doesSomething.call, or a few other things).

Yeah that's my understand too, so how do I expose a function that utilizes the class to return a value?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

Yeah that's my understand too, so how do I expose a function that utilizes the class to return a value?

I'm only half a cup of coffee in to today, so I'm a little slow, but you want a "class method" that other components / functions can call on an *instance* of a component to instruct that component to "do a thing" or get a value from that instance? Or do you just want a class method that does stuff that isn't related to a specific instance? I suspect the former, but again... not enough coffee.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.




edit: nevermind

piratepilates fucked around with this message at 15:25 on Mar 8, 2017

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Knifegrab posted:

Yeah that's my understand too, so how do I expose a function that utilizes the class to return a value?

I don't actually know how javascript classes work exactly, but if it's similar to Java classes, there is a slight difference whether you want to call a static method or an instance method.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Lumpy posted:

I'm only half a cup of coffee in to today, so I'm a little slow, but you want a "class method" that other components / functions can call on an *instance* of a component to instruct that component to "do a thing" or get a value from that instance? Or do you just want a class method that does stuff that isn't related to a specific instance? I suspect the former, but again... not enough coffee.

gently caress, yeah I guess I need the method for the instance because it has to manipulate state. The component will only exist once and it is a top level piece so it will always be there.

In the old jQuery widget paradigm, the method was called using a jQuery selector, so it calls the method on the widgets instance, not sure how to replicate that behavior in react.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

gently caress, yeah I guess I need the method for the instance because it has to manipulate state. The component will only exist once and it is a top level piece so it will always be there.

In the old jQuery widget paradigm, the method was called using a jQuery selector, so it calls the method on the widgets instance, not sure how to replicate that behavior in react.

Why wouldn't you fire off an action from anywhere in the app that updates the store / state? Are you not using a store or something? (or is that component your store :ohdear:)

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Lumpy posted:

Why wouldn't you fire off an action from anywhere in the app that updates the store / state? Are you not using a store or something? (or is that component your store :ohdear:)

There is tragically no store used currently in the product. Kill me

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

There is tragically no store used currently in the product. Kill me

Well..... uh.... um......

Yeah, I got nothing.

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

Lumpy posted:

Why wouldn't you fire off an action from anywhere in the app that updates the store / state? Are you not using a store or something? (or is that component your store :ohdear:)

If it's a single component you don't need a store at all. Internal state is a perfectly fine store.

Triggering internal component stuff from functions like this is the antithesis of react. The idea is for components to have no side effects of their own and change the incoming props if you need it to be different. This gets a bit hazy without a store, which is the point you'd either look at redux or refactor the whole thing. With redux you could do this v easily but for a single component it can feel a bit heavy handed.

Of course this is JS so it's all heavy handed

Xom
Sep 2, 2008

文化英雄
Fan of Britches
My rewrite of my project is live. Special thanks to biznatchio, Bruegels Fuckbooks, and everybody else here :toot:

Odette
Mar 19, 2011

Xom posted:

My rewrite of my project is live. Special thanks to biznatchio, Bruegels Fuckbooks, and everybody else here :toot:

The two demo cards on the left & right of the top look a bit blurry. Is that expected? I have a 1440p screen, so that may be a contributing factor.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

necrotic posted:

If it's a single component you don't need a store at all. Internal state is a perfectly fine store.



Yes, but he's wanting to read that component's state from other components. So he wants to treat it like a...... store.

Xom
Sep 2, 2008

文化英雄
Fan of Britches

Odette posted:

The two demo cards on the left & right of the top look a bit blurry. Is that expected? I have a 1440p screen, so that may be a contributing factor.
That's just a static page, and I made the images low-res, so yes. Did you try running the demo? I should probably bold that link.

Edit: Should I put full-res images instead?

Xom fucked around with this message at 03:52 on Mar 10, 2017

Odette
Mar 19, 2011

Xom posted:

That's just a static page, and I made the images low-res, so yes. Did you try running the demo? I should probably bold that link.

Edit: Should I put full-res images instead?

gently caress around with png & pngquant, see where that gets you.

nielsm
Jun 1, 2009



I've been toying around with WebGL for a simple visual effect. I've never properly worked with OpenGL before, and it's also my first time writing something to process quite this amount of data in JS.
So the problem/question I have is regarding performance.

Here is what I have currently. Parts of it are just copy-paste jobs from other sites. The idea is you pick an arbitrary file (various non-compressed binary files tend to look the best), pick a matrix resolution, and it renders a height field of the first couple kb of the file.

I've tried using Firefox's profiler on it, and as far as I can tell the majority of the time is spent generating the geometry, probably because I allocate a large number of regular arrays and Float32Array objects. (See the drawSingleValue and cubeTriangles functions.) Does my analysis sound right? What do others do here, since obviously everyone else can get frame times well below 50 ms.
Or are my expectations completely off for processing a 1024x512 field generating 6.2 Mtris?

nielsm
Jun 1, 2009



Answering my own question: Yes it was the allocations that were expensive. After getting some sleep, I reorganized the code to only allocate a single Float32Array for the entire drawing loop and filling/re-filling it with a whole row of cubes at a time. That brought my run time at 1024x512 down from 2100 ms to 400 ms. It's still rather bad I think, but already much better.

My new drawing code:
JavaScript code:
            function cubeTriangles2(dst, idx, x1, y1, z1, x2, y2, z2) {
                function p(x,y,z) {
                    dst[idx++] = x;
                    dst[idx++] = y;
                    dst[idx++] = z;
                }
                // top
                p(x1, y1, z1);   p(x2, y1, z1);   p(x1, y2, z1);
                p(x2, y1, z1);   p(x2, y2, z1);   p(x1, y2, z1);
                // front
                p(x1, y1, z1);   p(x2, y1, z1);   p(x1, y1, z2);
                p(x2, y1, z1);   p(x2, y1, z2);   p(x1, y1, z2);
                // left
                p(x1, y1, z1),   p(x1, y2, z1),   p(x1, y1, z2);
                p(x1, y2, z1);   p(x1, y2, z2);   p(x1, y1, z2);
                // right
                p(x2, y2, z1);   p(x2, y1, z1);   p(x2, y2, z2);
                p(x2, y1, z1);   p(x2, y1, z2);   p(x2, y2, z2);
                // back
                p(x1, y2, z1);   p(x1, y2, z2);   p(x2, y2, z1);
                p(x2, y2, z1);   p(x1, y2, z2);   p(x2, y2, z2);
                // bottom
                p(x1, y1, z2);   p(x1, y2, z2);   p(x2, y1, z2);
                p(x2, y1, z2);   p(x1, y2, z2);   p(x2, y2, z2);
                return idx;
            }

// ... snip ...

                var triangles = new Float32Array(w*6*2*3*3); // 'w' cubes with 6 sides of 2 triangles, each is 3x vec3 points
                for (var y = 0; y < h; y++) {
                    var idx = 0;
                    for (var x = 0; x < w; x++) {
                        var byteval = data[x+y*w]/255.0;
                        idx = cubeTriangles2(triangles, idx, x, y, byteval, x+1, y+1, -1);
                    }
                    gl.bufferData(gl.ARRAY_BUFFER, triangles, gl.STREAM_DRAW);
                    gl.drawArrays(gl.TRIANGLES, 0, triangles.length/3);
                }

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Are you sure you can't just call drawArrays once instead of h separate times?

nielsm
Jun 1, 2009



Jabor posted:

Are you sure you can't just call drawArrays once instead of h separate times?

I could, but I'm not sure how much more there is to win in putting w*h*12 triangles at once instead of w*12 triangles h times. The Float32Array allocation would then be 72 MB instead of 144 kB, in my 1024x512 case.

Edit: Just tried changing to preallocating a single Array Buffer in the GL context for the complete geometry, and then filling it row by row using the smaller single-row Float32Array. That lets me do just a single drawArrays call at the end. Profiler says it's no faster, and may even be slower.

nielsm fucked around with this message at 13:33 on Mar 11, 2017

MrBadidea
Apr 1, 2009
I think the point there is more "are you sure generating the complete geometry for the entire display is what you need to be doing".

If every renderable object is functionally a cube, then you don't need n*cubes to be in the geometry buffer; you only need to draw one cube in n places. See: instancing.

TheFluff
Dec 13, 2006

FRIENDS, LISTEN TO ME
I AM A SEAGULL
OF WEALTH AND TASTE
I'm a web-man with some experience who's mostly been around Python in the last few years, but recently I got roped into a node project where I have full design freedom for the backend. I've done async stuff in other languages but after after staring long and hard at BluebirdJS, ES6 promises and async/await I concluded that the way I felt most comfortable with and that fit best into the Express framework and the rest of Node stuff was using the async library and going all in on the functional paradigm, so now my functions that interact with the database have started to look like this little snippet:

JavaScript code:
let plaintextToHash = async.seq(
  auth.validatePlaintext,
  auth.hashPlaintext
);

let mutatePasswordToHash = function (columns, callback) {
  plaintextToHash(columns.password, (err, hash) => {
    if (err) { return callback(err); }
    columns.password = hash;
    return callback(null, columns);
  });
};

// returns an async function that creates a user
let hashPassAndCreate = async.seq(          // value passed to next function:
  async.asyncify(_.pick(createProperties)), // -> columns required for creation
  mutatePasswordToHash,                     // -> same object, but with password mutated to hashed form
  _.partial(create, [{}])                   // -> saved user object
);
I don't particularly like the implicit parameters, hence all the comments, but I didn't like the promise idea of making async code look like it's synchronous either. Now for my question: in what way is this inevitably going to bite me in the rear end? I already know one caveat, namely that it's probably going to confuse people who are used to promises, that is the by far most common way of doing these things. Right now I'm the only backend dev on this project but that may change in the future and it's probably going to be maintained by others after I leave it. I can still change my mind though, so please tell me now about what kind of huge rear end traps I'm about to fall into.

TheFluff fucked around with this message at 20:14 on Mar 13, 2017

Roadie
Jun 30, 2013

TheFluff posted:

but I didn't like the promise idea of making async code look like it's synchronous either.
I don't really understand how promises are supposed to make something "look like it's synchronous". The whole point of the promise structure is that (barring use of async/await) you're for the most part just breaking everything down into the separate parts that are synchronous, with the asynchronous breakpoints between them being the resolving/rejecting of the promise. Async/await is just sugar over "the rest of this function is going to be in a then clause anyway".

TheFluff posted:

I can still change my mind though, so please tell me now about what kind of huge rear end traps I'm about to fall into.
Literally everyone but you is going to use promises, so every time you ever use any kind of other library with anything that's ever asynchronous you'll have write weird wrappers around everything.

Roadie fucked around with this message at 20:58 on Mar 13, 2017

TheFluff
Dec 13, 2006

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

Roadie posted:

I don't really understand how promises are supposed to make something "look like it's synchronous". The whole point of the promise structure is that (barring use of async/await) you're for the most part just breaking everything down into the separate parts that are synchronous, with the asynchronous breakpoints between them being the resolving/rejecting of the promise. Async/await is just sugar over "the rest of this function is going to be in a then clause anyway".
I think it's how you write it in a way that kinda looks imperative that throws me off. Each part of the doSomething().then().then() chain is of course async, but when I look at it, it feels like I'm looking at an imperative statement and not a function chain composition, which is what it actually represents. async.seq(function1, function2, function3) effectively does the exact same thing as function1().then(function2).then(function3) - except it doesn't start execution immediately but rather returns a function that will - but I think I look the look of the former better. This is of course just a matter of taste, though.

Then there's using exceptions for error handling, which also feels extremely loving synchronous even though it's actually kinda not in the context of promises. This became very apparent when I noticed es6 promises default to silently swallowing exceptions unless you remember to explicitly catch them, something that made me deeply suspicious of the entire concept, but it turns out most people are using bluebird which at least defaults to logging unhandled rejections and has the possibility of installing a global event handler for taking care of those (which in itself is kinda uuuuurgh, but hey, it's better than silently swallowing the error). At least with callbacks there's no question about what's going to happen if I throw (the node process is going to crash, and sometimes that's exactly what I want). Then again with callback-based flow I have to think about not calling the callback more than once and so on and so forth...

Roadie posted:

Literally everyone but you is going to use promises, so every time you ever use any kind of other library with anything that's ever asynchronous you'll have write weird wrappers around everything.
Eh. Bluebird promises have an asCallback() method natively, and the "weird wrapper" for every synchronous function is async.asyncify().

I'm noticing I'm having a hard time articulating exactly why I dislike promises, which maybe means I don't really have any reason not to use them. On the other hand, I do like the functional composition style of async better. It goes quite well together with lodash/fp and currying etc, but I could probably shoehorn that into promises as well. That's kinda why I asked. vOv

e: really, I think what's making me suspicious is that I don't feel like I understand promises. There's really not much much to them at all, but there's something that unsettles me. Brains, man.

TheFluff fucked around with this message at 22:10 on Mar 13, 2017

Roadie
Jun 30, 2013

TheFluff posted:

e: really, I think what's making me suspicious is that I don't feel like I understand promises. There's really not much much to them at all, but there's something that unsettles me. Brains, man.

Probably the biggest weirdness to wrap your head around is that inside the function for a promise, you can return a value that gets passed in to the next then function, or you can return a Promise which gets evaluated before the next Promise in the chain does (which itself can return a Promise, which itself can return a Promise, which itself can...).

Some of the conceptual weirdness there goes away if you use async/await for that, since that makes "returns a value" and "returns a Promise that resolves to a value" syntactically identical except for the async decorator.

Roadie fucked around with this message at 18:49 on Mar 15, 2017

Thermopyle
Jul 1, 2003

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

What helped me internalize promises was writing my own implementation. It's not hard to write a compliant enough for a toy implementation, and it cleared up a lot of my thinking around them.

There's several blog posts about doing this if you need help getting started, but I'm phone posting so you'll have to Google for yourself.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
So I am writing a component that generates forms. It takes in a prop that defines the structure of the form (how many fields and what type).

I am using this prop to inform the initial state so I can then keep track of all the values of the fields in state. However, as this component is driven by a parent component, the prop that feeds this info changes. As such when it is initially mounted its state will effectively be empty until a user selects what type of form to present.

At that point though the form is still effectively empty, since the prop is updating but the component isn't remounting. What is the best practice here to get my state to update (drop old state values and add new state values)? I know state is supposed to never be acted upon directly so I am not sure what to do.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

So I am writing a component that generates forms. It takes in a prop that defines the structure of the form (how many fields and what type).

I am using this prop to inform the initial state so I can then keep track of all the values of the fields in state. However, as this component is driven by a parent component, the prop that feeds this info changes. As such when it is initially mounted its state will effectively be empty until a user selects what type of form to present.

At that point though the form is still effectively empty, since the prop is updating but the component isn't remounting. What is the best practice here to get my state to update (drop old state values and add new state values)? I know state is supposed to never be acted upon directly so I am not sure what to do.

I'm assuming you are using some sort of framework maybe, but you are not telling us, so it is tough to help. I can guess at which one you are using, but we all know what Benny Hill says about assuming.

necrotic
Aug 2, 2005
I owe my brother big time for this!
There's a componentWillReceiveProps lifecycle hook for exactly that case. Look up the lifecycle hooks.

Edit assuming react

Adbot
ADBOT LOVES YOU

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
Yeah sorry guys, I was in fact using react and I used the componentWillRecieveProps hook to update the state on re-instancing.

Now I've got a UI question!

I have a comment system where users can leave comments on different pages. I store the plain text (sanitized) into a database, and when I display it I retrieve it from a database. I run the text to be returned through escape-html npm module to ensure that people cannot html/script inject my pages. However then when I display the text within my content it appears as this:

code:
Weaver&#39;s a tree. Once he has a &quot;young weaver&quot; attached to himself, he can&#39;t jump
Obviously for display purposes this is super ugly. I need to prevent quotes/apostrophes/square brackets etc from ebing interpolated as html but I also want them display nicely and not as the weird item they are being displayed as. Any ideas?

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