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
reversefungi
Nov 27, 2003

Master of the high hat!

Knifegrab posted:

So I have been working with react for quite some time, and for the most part all of my components are self contained. I am now replacing an old JQuery widget, and the way it worked was it was fairly self contained but them exposed some functions via JQuery so other parts of the code could add data to the container.

I am not entirely sure how to do this with React. Would my only bet here be to do it via a redux-like store?

Have you read Thinking in React before from the docs? https://facebook.github.io/react/docs/thinking-in-react.html

I have a feeling this should give you a good start on how to share data across components. You don't necessarily need redux yet.

reversefungi fucked around with this message at 17:21 on Aug 14, 2017

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.

The Dark Wind posted:

Have you read Thinking in React before from the docs? https://facebook.github.io/react/docs/thinking-in-react.html

I have a feeling this should give you a good start on how to share data across components. You don't necessarily need redux yet.

I believe I am familiar, but the issue is this is a very top level component, and we don't pass inheritence throughout the product, so I don't know how to pass this prop to all the bottom level items that may need access to its contents (or to modify them)

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

Knifegrab posted:

I believe I am familiar, but the issue is this is a very top level component, and we don't pass inheritence throughout the product, so I don't know how to pass this prop to all the bottom level items that may need access to its contents (or to modify them)

That sounds like a use-case for a redux-like store managed outside of the component hierarchy (and I'd recommend just using redux). You can make it work with contexts, but its not recommended.

Dominoes
Sep 20, 2007

You probably want to use global state, like Redux; ie when you change the store via a dispatch, your component updates. Alternatively, you could pass a prop down the component hierarchy.

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

Dominoes posted:

Alternatively, you could pass a prop down the component hierarchy.

If the component requiring the data isn't really deep this is honestly the best approach. If you have to pass it down like 5+ levels it becomes problematic from a usability perspective (though still works fine from a "do the stuff, react" perspective).

Using the redux approach in that scenario also has the benefit of only re-rendering the tree where the data is used, instead of all of it.

MrMoo
Sep 14, 2000

Anyone recommend a non-terrible library for extracting the background colour of an image? I have found a few that are poorly written but generally rely on a third party to do the actual logic, e.g. modified median cut quantization. It's not simply the dominant colour of the entire image though as I'm dealing with logos with mainly transparent backgrounds which would produce an incorrect result.



So I can create a canvas taking the full available height, center the actual logo and backfill with yellow.

Similar example:

MrMoo fucked around with this message at 18:07 on Aug 15, 2017

Ranzear
Jul 25, 2013

Just getImageData and scan pixels until you find one with alpha ~1.0? Won't quite work with a 'bare' logo, like if it has a black outline. You could also try an invert or complimentary based on that.

geeves
Sep 16, 2004

Ranzear posted:

Just getImageData and scan pixels until you find one with alpha ~1.0? Won't quite work with a 'bare' logo, like if it has a black outline. You could also try an invert or complimentary based on that.

That reminds me a bit of this answer from stack overflow: https://stackoverflow.com/questions/12995378/is-there-a-proper-algorithm-for-detecting-the-background-color-of-a-figure

I had looked into this a year or two ago wanting to do the same thing, but it was instead settled on using a pattered background image and merged the two together for thumbnail display so I never got to test it out.

MrMoo
Sep 14, 2000

Some really inconvenient logos to work with, I ended up scanning alternating pixels on the top second two lines and bottom last-but one pair of lines and comparing the values to prevent breaking on a asymmetric gradient.

:lol:




This is functional for logos with solid colours otherwise a more astute algo is required.
JavaScript code:
this._logo_ctx.clearRect(0, 0, this._logo_canvas.width, this._logo_canvas.height);
const top = (this._logo_canvas.height - imageBitmap.height) / 2;
this._logo_ctx.drawImage(imageBitmap, 0, top);
const d1 = this._logo_ctx.getImageData(0, top + 1, imageBitmap.width, 2);
const d2 = this._logo_ctx.getImageData(0, imageBitmap.height - 2, imageBitmap.width, 2);
let r = 0, g = 0, b = 0;
for(let i = 0, j = 0; i < imageBitmap.width; i+=2, j+=16) {
        r += d1.data[j]   + d2.data[j];
        g += d1.data[j+1] + d2.data[j+1];
        b += d1.data[j+2] + d2.data[j+2];
}
r = ~~(r/imageBitmap.width);
g = ~~(g/imageBitmap.width);
b = ~~(b/imageBitmap.width);
if(r === d1.data[0] && g === d1.data[1] && b === d1.data[2]) {
        this._logo_ctx.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
        this._logo_ctx.fillRect(0, 0, this._logo_canvas.width, top + 1);
        this._logo_ctx.fillRect(0, top + imageBitmap.height - 1, this._logo_canvas.width, top + 1);
}

MrMoo fucked around with this message at 21:43 on Aug 15, 2017

stoops
Jun 11, 2001
Wondering if anyone can help with this. Even if its pseodcode, I may be able to code it.

I will have an array of numbers

[0, 116, 131, 1550] and i will have a row number.

I need to seperate the numbers in chunks. Inbetween each number, think of it as a box.

In this example, with 1 row, my output would be

box 1 = 0,116
box 2 = 116,131
box 3 = 131,1550

If I have 2 rows, output would be:

box 1 = 0,116
box 2 = 116,131
box 3 = 131,1550
box 4 = 0,116
box 5 = 116,131
box 6 = 131,1550

Any help is appreciated.

zombienietzsche
Dec 9, 2003
I'm not sure what your chunking algorithm is, but the rest can look something like this:

code:
var rowNumber = 10;
var chunks = magically_separate_into_chunks();

var boxes = [];
boxes[0] = chunks[0]; // aything % 0 = NaN
for (var i = 1; i < rowNumber; i++) {
  boxes[i] = chunks[i % chunks.length];
}

Munkeymon
Aug 14, 2003

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



It looks like the chunking is just

JavaScript code:
chunks = [];
for (var j = 1; j < list.length; ++j) {
  chunks.push([line[i-1], line[i]]);
}

Snak
Oct 10, 2005

I myself will carry you to the Gates of Valhalla...
You will ride eternal,
shiny and chrome.
Grimey Drawer
Hey everyone, I'm trying to make a basic image filtering application that displays a local file, parses it, does some basic manipulation, and displays the result.

The biggest problem that I'm having is in displaying the result. Using HTML5's file API, it's easy to display the local file, then use a FileReader to get the image data and redraw it on a canvas to display the result. The problem is that the source image is displayed as an img tag, which handles dynamic resizing just fine, but the result is drawn in a canvas, and I can't figure out how to get it to play nice with dynamic resizing at all. I have it set up to have the canvas match the size of the source image when it's drawn, and that works fine, but I can't get its size to ever update after that. It's a huge mess.

The best way to do all of this is if I could turn the post-processed img object into a new file object and provide it as a source to an img tag. Then the input and output of the app would be displayed and formatted using the exact same mechanisms and be completely consistent.

Is there a way to do this? Obviously I can't create a local file on the user's system without their explicit action, so I guess what I'm asking is, is there a way for the locally running JS to serve a file to an img tag? It sounds kind of crazy when I say it like that, but I'm getting desperate here.

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.

Snak posted:

Hey everyone, I'm trying to make a basic image filtering application that displays a local file, parses it, does some basic manipulation, and displays the result.

The biggest problem that I'm having is in displaying the result. Using HTML5's file API, it's easy to display the local file, then use a FileReader to get the image data and redraw it on a canvas to display the result. The problem is that the source image is displayed as an img tag, which handles dynamic resizing just fine, but the result is drawn in a canvas, and I can't figure out how to get it to play nice with dynamic resizing at all. I have it set up to have the canvas match the size of the source image when it's drawn, and that works fine, but I can't get its size to ever update after that. It's a huge mess.

The best way to do all of this is if I could turn the post-processed img object into a new file object and provide it as a source to an img tag. Then the input and output of the app would be displayed and formatted using the exact same mechanisms and be completely consistent.

Is there a way to do this? Obviously I can't create a local file on the user's system without their explicit action, so I guess what I'm asking is, is there a way for the locally running JS to serve a file to an img tag? It sounds kind of crazy when I say it like that, but I'm getting desperate here.

You can totally resize an image with canvas and have it look smooth.

You're probably better off keeping the actual canvas itself the same dimensions, and just using drawImage to scale (as it takes height and width parameters, so you can tell it to draw whatever size you want.

If you change the actual width/height of the canvas, the canvas will be cleared, and you will have to call drawImage again - this will cause flickering unless you do something like keep a temporary canvas during the actual resize operation.

Snak
Oct 10, 2005

I myself will carry you to the Gates of Valhalla...
You will ride eternal,
shiny and chrome.
Grimey Drawer
I can't even get that to work. When I call the draw image function again, it just never draws. I think because it's trying to getContext again which returns null if you reuse it.

God I hate frontend poo poo.

Okay, so I should make the canvas some theoretical maximum for my site, and then draw whatever size I need? I will give that a shot, thanks.

edit: Like, forget it looking smooth, it seems to be a total crapshoot what inputImage.clientWidth returns at any given time. Sometime it correctly returns returns the displayed image's width, and sometime it returns the absolute size of the image. when I try to use it to update the size of the output image on windo resize, ir returns the width of the input image as it was before the resize event. Sort of. It returns the before resize width and the after resize height. So I need another "onload" somewhere.

I guess I have a fundamental question about JS that I haven't been able to find the answer to with google: What conditions trigger the loading of an element? When does the browser say "this elements exists, it's time to start loading it"? Because most of my problems with JS revolve around not knowing when an element is being reloaded and when I'm changing things that don't trigger a reload.

Snak fucked around with this message at 01:57 on Aug 17, 2017

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.

Snak posted:

I can't even get that to work. When I call the draw image function again, it just never draws. I think because it's trying to getContext again which returns null if you reuse it.

God I hate frontend poo poo.

Okay, so I should make the canvas some theoretical maximum for my site, and then draw whatever size I need? I will give that a shot, thanks.

If you can throw up a code sample or jsfiddle or something, I might be able to help.

Snak
Oct 10, 2005

I myself will carry you to the Gates of Valhalla...
You will ride eternal,
shiny and chrome.
Grimey Drawer

Bruegels Fuckbooks posted:

If you can throw up a code sample or jsfiddle or something, I might be able to help.

Yeah, I'll do that, thanks. While I'm working on that, I edited my post with more basic questions about JS.

https://jsfiddle.net/8t1zuewg/

Good news and bad news: While trying to figure out why the output of jsfiddle is different from my local output, I fixed the dynamic resizing just fine. The problem persists, however, that I can't make the image the correct size in the first place. In JS fiddle, the image is drawn smaller than it should be, while in my regular browser, the image is drawn larger than it should be.

The sizing is done here, lines 30-37
code:
var sourceImage = document.getElementById("inputImage");
    
console.log("getContext");
var context = canvas.getContext("2d");
    
console.log("drawImage");
//context.drawImage(sourceImage, 0, 0, canvas.width, canvas.height);
context.drawImage(sourceImage, 0, 0, sourceImage.clientWidth, sourceImage.clientHeight);
Please forgive all of the horrible console.log outputs, I can't use netbeans debugger and chrome's devtools at the same time, so I did a bunch of bad console outputs so I could see what was going on, since netbeans wasn't showing me errors that chrome was.


edit: This new problem is because I'm now using CSS to change the display size of the canvas, which also correctly adjusts the displays size of what's drawn on the canvas, BUT when you draw to the canvas, you're drawing on the actual size of the canvas. I think.

So if I just make the canvas the actual size of the image and draw on the whole thing and change its display size with css, that should work.

edit again: Which it did.

Thanks so much. I really need to get an actual rubber ducky. Most of my confusion stemmed from mixing up the canvas's css width with it's DOM width property. Once I realized that, it all made sense.

Snak fucked around with this message at 02:35 on Aug 17, 2017

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.

Snak posted:

Yeah, I'll do that, thanks. While I'm working on that, I edited my post with more basic questions about JS.

https://jsfiddle.net/8t1zuewg/

Good news and bad news: While trying to figure out why the output of jsfiddle is different from my local output, I fixed the dynamic resizing just fine. The problem persists, however, that I can't make the image the correct size in the first place. In JS fiddle, the image is drawn smaller than it should be, while in my regular browser, the image is drawn larger than it should be.

The sizing is done here, lines 30-37
code:
var sourceImage = document.getElementById("inputImage");
    
console.log("getContext");
var context = canvas.getContext("2d");
    
console.log("drawImage");
//context.drawImage(sourceImage, 0, 0, canvas.width, canvas.height);
context.drawImage(sourceImage, 0, 0, sourceImage.clientWidth, sourceImage.clientHeight);
Please forgive all of the horrible console.log outputs, I can't use netbeans debugger and chrome's devtools at the same time, so I did a bunch of bad console outputs so I could see what was going on, since netbeans wasn't showing me errors that chrome was.


edit: This new problem is because I'm now using CSS to change the display size of the canvas, which also correctly adjusts the displays size of what's drawn on the canvas, BUT when you draw to the canvas, you're drawing on the actual size of the canvas. I think.

So if I just make the canvas the actual size of the image and draw on the whole thing and change its display size with css, that should work.

edit again: Which it did.

Thanks so much. I really need to get an actual rubber ducky. Most of my confusion stemmed from mixing up the canvas's css width with it's DOM width property. Once I realized that, it all made sense.

https://www.youtube.com/watch?v=m6PxRwgjzZw

Munkeymon
Aug 14, 2003

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



Serialize the canvas with canvas.toDataURL to a data URL and set that as an IMG tag's src attribute.

It's probably possible to go straight from file data to a data URL without the canvas because I think the data section is just the raw bytes base-64 encoded.

MrMoo
Sep 14, 2000

Normally the createImageBitmap(blob) promise will do that.

Sab669
Sep 24, 2009

I'm trying to build a list of unique strings and then compare another collection to that list. But I'm getting hung up on the "unique" part.

code:

function CheckSelection(gridName)
{
    //Get records from my grid control
    var view = $("#" + gridName).data("kendoGrid").data source.view();

    //Array to store unique values from a grid column
    var listOfGroups = [];

    //Integer to track the next index
    var listIndex = 0;

    for (var i = 0; i < view.length; i++)
    {
        //Check if the list already contains the 'GROUP' value from the current view record
        if (listOfGroups[view[i].GROUP])
            continue;

        //If the list does NOT contain the current record's value, add it
        listOfGroups[listIndex] = view[i].GROUP;

        //Increment the array index tracker
        listIndex = listIndex + 1;
    }
}

This grid has 3 rows, with the following GROUP values: "1", "1", "2".

I want my listOfGroups to contain 2 elements: "1", and "2".

The above code gives me three elements: "1", "1", "2".

The if statement never evaluates to true. I expected it to equal true on the second iteration, because "1" has already been added to my list.

If I use a breakpoint and try to evaluate listOfGroups["1"], I get undefined. So I think that's happening is that it's casting the string to an integer and then looking for the element at index 1, which does not exist.

So how can I check if my array already contains that value?

darthbob88
Oct 13, 2011

YOSPOS

Sab669 posted:

I'm trying to build a list of unique strings and then compare another collection to that list. But I'm getting hung up on the "unique" part.

code:
function CheckSelection(gridName)
{
    //Get records from my grid control
    var view = $("#" + gridName).data("kendoGrid").data source.view();

    //Array to store unique values from a grid column
    var listOfGroups = [];

    //Integer to track the next index
    var listIndex = 0;

    for (var i = 0; i < view.length; i++)
    {
        //Check if the list already contains the 'GROUP' value from the current view record
        if (listOfGroups[view[i].GROUP])
            continue;

        //If the list does NOT contain the current record's value, add it
        listOfGroups[listIndex] = view[i].GROUP;

        //Increment the array index tracker
        listIndex = listIndex + 1;
    }
}
This grid has 3 rows, with the following GROUP values: "1", "1", "2".

I want my listOfGroups to contain 2 elements: "1", and "2".

The above code gives me three elements: "1", "1", "2".

The if statement never evaluates to true. I expected it to equal true on the second iteration, because "1" has already been added to my list.

If I use a breakpoint and try to evaluate listOfGroups["1"], I get undefined. So I think that's happening is that it's casting the string to an integer and then looking for the element at index 1, which does not exist.

So how can I check if my array already contains that value?
Well, Array.prototype.includes is made for this use case, but it's not supported by older browsers. If that's an issue, Array.prototype.indexOf works for the same purpose, but is clumsier.

necrotic
Aug 2, 2005
I owe my brother big time for this!
Arrays get really funky if you assign string keys (which is 100% possible). What you're doing here is trying to read listOfGroups["1"] instead of checking if the array includes the value "1". As mentioned above there's the new include method, or usage of indexOf. If the number of unique groups can be very large you may want to look at a using a map to track what's already included instead, but that's not an issue until you're looking at many thousands of unique groups.

edit: Also, you don't need to track listIndex at all; just use listOfGroups.push(view[i].GROUP) when adding a new group.

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
Also, js object keys are essentially a set so you could just use that property if all you care about is string uniqueness.

necrotic
Aug 2, 2005
I owe my brother big time for this!
In that case you'll want to use Object.prototype.hasOwnProperty instead of listOfGroups[key], the latter would also give you functions on the Object prototype if a group name collides with one.

Dominoes
Sep 20, 2007

Check out Lodash's uniq function.

LP0 ON FIRE
Jan 25, 2006

beep boop
I'm trying to capture an image at a certain time in a YouTube video. An answer on Stack Overflow gave me an impression that the YouTube iframe api had the capability, but I can't find anything about it that lets you do this.

For reference, the api is here: https://developers.google.com/youtube/iframe_api_reference

There's a bunch of sites that let you do this, but maybe they are doing something on the server side and not just JavaScript?

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'm using axios for file uploads. I have created a React Component that exists for a file uploading (it displays the filename and progress) because you can upload multiple files at once.

When doing so I create an axios request per file:

code:
axios({
   ...
   uploadProgress: () => //some function
});
the uploadProgress function is the part that I use to track the progress of the upload (obv) but I cannot figure out how to pass that to my component.

Obviously I could create an elaborate array in the parent class that details the files names and progresses but that seems like a bad approach. I'd rather have the component update itself on the upload progress than upload an entire array of uploads every time one has progress (the # of uploads is dynamic it would have to be an array).

But I cannot figure out how to pass the uploadProgress binding action to the child component. Can anyone help?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

I'm using axios for file uploads. I have created a React Component that exists for a file uploading (it displays the filename and progress) because you can upload multiple files at once.

When doing so I create an axios request per file:

code:
axios({
   ...
   uploadProgress: () => //some function
});
the uploadProgress function is the part that I use to track the progress of the upload (obv) but I cannot figure out how to pass that to my component.

Obviously I could create an elaborate array in the parent class that details the files names and progresses but that seems like a bad approach. I'd rather have the component update itself on the upload progress than upload an entire array of uploads every time one has progress (the # of uploads is dynamic it would have to be an array).

But I cannot figure out how to pass the uploadProgress binding action to the child component. Can anyone help?

Give each request an ID, store them in a map with any other data in the components state, then update as needed, and delete the key when the request finishes. When the object is empty, there's no requests going on.

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:

Give each request an ID, store them in a map with any other data in the components state, then update as needed, and delete the key when the request finishes. When the object is empty, there's no requests going on.

I'm afraid I don't follow :(

necrotic
Aug 2, 2005
I owe my brother big time for this!
Are you using redux or similar for state? If yes then hook into that to update data about a request identified using a randomly unique ID (uuid or even just a random number). If you're using internal state only you can use the parent components state for this, assuming you are calling axios from there.

I'd post pseudo code but I'm on a phone.

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Lumpy posted:

Give each request an ID, store them in a map with any other data in the components state, then update as needed, and delete the key when the request finishes. When the object is empty, there's no requests going on.

Say you make n requests to do something. You could create a map of objects that track them. As the responses come in, you mark it done, and when all items in map have done === true, all of them are done. In the above case, he's just removing them from the map/array instead of flagging it done, but the same thing.

code:
	
	let map = {};
	
	for (let r of requests) {
		let id = createGuid{};
		let myRequest = { id: id, done: false };
		map[id] = myRequest;
		
		let p = makeRequest(r);
		p.then( (res) => { myRequest.done = true; };
	}

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

I'm afraid I don't follow :(

Since your question didn't have quite enough info for me to grasp your exact situation, this might not fully apply to your use case, but it should at least give you the gist of what I was suggesting (from my phone, so that's why it wasn't very fleshed, out, so sorry for any confusion!)

Assuming we have Component A that wraps a bunch of component Rs.
Assuming each component R is a file upload component that handles a single file upload.

Assuming that you are asking 'How does A learn about what's happening in each R':

Component A has a map uploads: {} in it's internal state (or in the application state if other parts of the app care)

When you mount a new child R component, you pass it a unique ID, an handleUploadProgress , and if axios has them, handleUploadStart and handleUploadEnd (not sure if axios uses one callback for all of those or has separate functions) and add that ID to your uploads map with whatever data you want to track about that upload.

then each R can do:

JavaScript code:
axios({
   ...
   uploadProgress: ( _axoisProgress ) => {
       // any component R code here if needed....
       this.props.handleUploadProgress( this.props.myUID, _axiosProgress )
   }
});
(or you could get fancy and pass the handleUploadProgress function with the ID baked in already so each R doesn't even have to know it has an ID)

and then Component A is aware of what is happening in every R and can update it's internal uploads state based on the ID of the R that is calling back.

You can remove IDs from the uploads map when they are done, and infer that when that object has no keys, you have no in-progress uploads. Or if you are re-using your Rs, just reset the state in your map to 'ready for upload' or whatever.

EDIT: Again, I made a bunch of assumptions about what you were trying for, so if they were off, please explain a bit more so I can help more better!

Lumpy fucked around with this message at 15:20 on Aug 30, 2017

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.
OK thank you all very much, that is very helpful. Really quick, does anyone know what to search for or how to find out what events I can bind to for certain packages? For instance, parts of this would be made easier if I could do:

code:

let request = axios(//request);

request.on('uploadProgress', () => {
   //do thing I want to do
});

as opposed to

code:
axios({
   //request,
   uploadProgress: () => {
      //do a thing I want to do
   },
});
because with the first example I can then pass the request variable to my children component for event subscribing. I do not know how to figure out what events a particular class fires and it doesn't seem to list any on the github page for axios.

necrotic
Aug 2, 2005
I owe my brother big time for this!
There is no standard around events so it's RTFM for good packages, or have fun digging through code for the rest.

Does axios even have events like that? I thought not since calling axios returns a promise.

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.

necrotic posted:

There is no standard around events so it's RTFM for good packages, or have fun digging through code for the rest.

Does axios even have events like that? I thought not since calling axios returns a promise.

I have no idea, which is why I'm asking. I read the github page and it seems to indicate no but I am wondering if I am thick and missing something obvious.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

OK thank you all very much, that is very helpful. Really quick, does anyone know what to search for or how to find out what events I can bind to for certain packages? For instance, parts of this would be made easier if I could do:

code:

let request = axios(//request);

request.on('uploadProgress', () => {
   //do thing I want to do
});

as opposed to

code:
axios({
   //request,
   uploadProgress: () => {
      //do a thing I want to do
   },
});
because with the first example I can then pass the request variable to my children component for event subscribing. I do not know how to figure out what events a particular class fires and it doesn't seem to list any on the github page for axios.

Axios would explicitly have to add event binding, which it does not according to it's docs. It's really a six of one, half dozen of another thing, though I think. Why can't you pass the request variable down if you have uploadProgress inside the configuration?

JavaScript code:
const requestDidAThing = progress => { ... };
const Fart => () => {
   const request = axios({ uploadProgress: requestDidAThing });
   return (
       <div> lol <Buttes request={ request } /> </div>
   )
};
Why does the child component get the actual request anyway? Seems like you'd want to pass in data *about* the request, not the actual request itself?

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:

Axios would explicitly have to add event binding, which it does not according to it's docs. It's really a six of one, half dozen of another thing, though I think. Why can't you pass the request variable down if you have uploadProgress inside the configuration?

JavaScript code:
const requestDidAThing = progress => { ... };
const Fart => () => {
   const request = axios({ uploadProgress: requestDidAThing });
   return (
       <div> lol <Buttes request={ request } /> </div>
   )
};
Why does the child component get the actual request anyway? Seems like you'd want to pass in data *about* the request, not the actual request itself?

Because I need the child component to keep its own state on uploadProgress, otherwise I am updating every single component anytime one component has upload progress. (there could be upwarsd of 50 uploads occuring in parallel)

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

Because I need the child component to keep its own state on uploadProgress, otherwise I am updating every single component anytime one component has upload progress. (there could be upwarsd of 50 uploads occuring in parallel)

Gotcha. A couple more random thoughts, then I'll shut up: Is there a reason the request can't originate / live entirely in the subcomponent? Are you *sure* they all re-render when one updates? (and is them all re-rendering an actual performance bottleneck?)

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.

Lumpy posted:

Gotcha. A couple more random thoughts, then I'll shut up: Is there a reason the request can't originate / live entirely in the subcomponent? Are you *sure* they all re-render when one updates? (and is them all re-rendering an actual performance bottleneck?)

It could, which is where my brain is headed now. I think when a component is mounted it will call the request, with a callback for when its done, and the parent component will just monitor the state of all children and clear them when all requests are complete. That way I can still bind to the uploadProgress.

It feels... wrong for some reason but I think its a sensible approach.

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