投稿時間:2023-04-25 07:07:29 RSSフィード2023-04-25 07:00 分まとめ(11件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 20代の4割「成長を実感できない」 会社への不満も https://www.itmedia.co.jp/business/articles/2304/25/news039.html itmedia 2023-04-25 06:30:00
Google カグア!Google Analytics 活用塾:事例や使い方 アルミサッシがすぐに外れるのを直した(戸車の交換方法) https://www.kagua.biz/family/diy/20230432a1.html 方法 2023-04-24 21:00:11
AWS AWS News Blog AWS Week in Review – April 24, 2023: Amazon CodeCatalyst, Amazon S3 on Snowball Edge, and More… https://aws.amazon.com/blogs/aws/aws-week-in-review-april-24-2023-amazon-codecatalyst-amazon-s3-on-snowball-edge-and-more/ AWS Week in Review April Amazon CodeCatalyst Amazon S on Snowball Edge and More…As always there s plenty to share this week Amazon CodeCatalyst is now generally available Amazon S is now available on Snowball Edge devices version of AWS Amplify Flutter is here and a lot more Let s dive in Last Week s Launches Here are some of the launches that caught my eye this past week Amazon … 2023-04-24 21:22:02
AWS AWS Partner Network (APN) Blog Designing High-Performance Applications Using Serverless TiDB Cloud and AWS Lambda https://aws.amazon.com/blogs/apn/designing-high-performance-applications-using-serverless-tidb-cloud-and-aws-lambda/ Designing High Performance Applications Using Serverless TiDB Cloud and AWS LambdaLearn how to build scalable cost effective and serverless microservices using TiDB Cloud and AWS Lambda TiDB Cloud is based on TiDB which is cloud native open source distributed SQL database with built in hybrid transactional and analytical processing HTAP that can handle multiple workloads seamlessly and effectively Explore how pairing TiDB Cloud with AWS Lambda enables you to build serverless event driven microservices further enhancing the scalability and cost effectiveness of your architecture 2023-04-24 21:38:48
海外TECH Ars Technica Google puts 10- to 30-year campus construction project “on hold” after 2 years https://arstechnica.com/?p=1933915 campus 2023-04-24 21:48:16
海外TECH DEV Community Updating React State Inside Loops https://dev.to/bytebodger/updating-react-state-inside-loops-2dbf Updating React State Inside LoopsI recently ran into a very nasty little conundrum with React I found a use case where I felt it was necessary to update React state variables inside a loop I initially had no idea how vexing it would be State Management Under The HoodBefore I dive into this problem there are a few basic facts that you need to understand about how React manages state variables This should be second nature to all of you salty old React vets out there But it s important to establish these ground rules before we dive in React state is asynchronousWhen you update a React variable the subsequent mutation occurs asynchronously You can prove it out with an example like this export const MyComponent gt const counter setCounter useState const increment gt setCounter counter console log counter counter return lt gt lt div gt Counter counter lt div gt lt button onClick increment gt Increment lt button gt lt gt From a UX perspective the example above works just fine Every time you click Increment the counter value updates However the console log output will always be one update behind This happens because the update occurs asynchronously And when the code hits the console log the value has not yet been updated React batches state updatesReact does a lot of work behind the scenes to optimize performance Normally this optimization doesn t really phase us Because the typical flow is A user performs some action like clicking a button The state variable is updated React s reconciliation process is triggered This process realizes that there s now a diff between the virtual DOM and the actual DOM React updates the actual DOM to reflect the changes in the virtual DOM In the vast majority of circumstances this all happens so fast as to appear to the naked eye as instantaneous But the good folks who built React also put in some safeguards to protect against those instances where a developer tries to fire off a rapid series of state updates Of course this optimization is by and large a very good thing But it can be baffling when you feel that those successive updates are truly necessary Specifically React goes out of its way to ensure that all state updates that are triggered within a loop will not actually be rendered until the loop has finished running A Case Study For State Updates Inside A LoopMy website does image color manipulation Although the functionality works precisely as designed this does present a few challenges Images have the potential to be large I could introduce some artificial limits on the size of the image file either in raw kilobytes or in height width dimensions but doing so would undermine much of the utility of the application The images are not being uploaded and processed on a server It s a single page application It runs entirely in the browser So I can t for example upload an image commence some intensive processing and then promise to email the user a link to the finished product when the process is complete The amount of time it takes to process an image is largely dependent upon the processing options that are chosen by the user For example processing an image with the RGB color space is much faster than using Delta E Dithering an image takes more time than if dithering is avoided So in theory I could introduce some artificial limits on the number of options available to the user But again this would undermine much of the utility of the application itself The simple fact is that sometimes I want to transform an image of a certain size and with a certain number of processor intensive options that s gonna take a little time to complete When that happens I don t want the user wondering if the application has crashed I want them to understand that everything is chugging along as planned and their newly processed image will be completed soon The Progress BarOne of the most time tested ways to let the user know that processing is continuing as planned is to give them some kind of progress bar Ideally that progress bar updates in real time as the code works through its machinations Of course this is nothing new at all Applications have been providing this type of user feedback for decades But when I tried to implement this in React with Material UI s lt CircularProgress gt component I ran into some really nasty headaches Because I don t want to confuse the matter by trying to drop you right into the middle of Paintmap Studio s code I ve instead created a simplified demo in CodeSandbox to illustrate the problem You can view that demo here The Problem IllustratedIn the Code Sandbox demo I ve created an artificially slow process to illustrate the issue When you load this demo it gives you a single button on the screen titled START SLOW PROCESS The idea is that once you click that button a somewhat lengthy process will be triggered But we don t want the user wondering whether the site s crashed So once the button is clicked we need to have an interstitial overlay shown on screen The overlay let s the user know that the process is underway and ideally gives them a dynamic progress indicator that lets them know how far the process is from being completed We ll start the illustration with App js App jsexport const AppState createContext export const App gt const progress setProgress useState const showProcessing setShowProcessing useState false return lt gt lt AppState Provider value progress setProgress setShowProcessing showProcessing gt lt UI gt lt AppState Provider gt lt gt App js is mostly just a wrapper for the UX However I m using the Context API to establish some state variables that will be useful in the downstream code progress represents the completion percentage of our SLOW PROCESS showProcessing determines whether the progress interstitial should be shown Now let s take a look at UI js UI jsexport const UI gt const appState useContext AppState const progress appState const slowProcess useSlowProcess const handleSlowProcessButton gt slowProcess runSlowProcess return lt gt lt Backdrop sx color fff zIndex theme gt theme zIndex drawer open appState showProcessing gt lt div className textAlignCenter gt lt Box sx display inline flex position relative gt lt CircularProgress color success value progress variant determinate gt lt Box sx alignItems center bottom display flex justifyContent center left position absolute right top gt lt Typography color white component div variant caption gt progress lt Typography gt lt Box gt lt Box gt lt br gt Slow Process Running lt div gt lt Backdrop gt lt Button onClick handleSlowProcessButton size small variant contained gt Start Slow Process lt Button gt lt gt First the named components in the JSX like lt Backdrop gt lt Box gt lt CircularProgress gt lt Typography gt and lt Button gt come from Material UI Second the component leverages the AppState context that was established in App js Specifically we ll be using showProcessing to toggle the visibility of the interstitial layer And we ll be using progress to show the user how far the SLOW PROCESS is from completion Finally this component also imports a custom Hook That Hook is called useSlowProcess Let s take a look at that useSlowProcess jsexport const useSlowProcess gt const appState useContext AppState const runSlowProcess async gt const startTime Math round Date now appState setProgress appState setShowProcessing true for let i i lt i for let j j lt j for let k k lt k for let l l lt l do the stuffs console log i appState setProgress i appState setShowProcessing false console log Elapsed time Math round Date now startTime seconds return runSlowProcess useSlowProcess returns a single function runSlowProcess runSlowProcess does the following It establishes a startTime so we can calculate just how long the SLOW PROCESS actually takes After playing with this repeatedly on Code Sandbox I can tell you that it takes seconds to complete It ensures that our progress variable starts at It then sets showProcessing to true so the user will see the in progress interstitial It then launches into the SLOW PROCESS The outer loop runs for iterations This means that every completion of the outer loop essentially means that we ve completed of the overall process After each percentage is completed we console log the current progress and we update the progress variable Remember that variable will be used to show the user how close we are to completion When the process is complete we set showProcessing back to false This should remove the in progress interstitial Finally we console log the total number of seconds that it took to complete the SLOW PROCESS So what happens when we run this code Well it s very disappointing When the user clicks the START SLOW PROCESS button there is no interstitial shown on screen This also means that the user sees no lt CircularProgress gt bar with no constantly updated completion percentage But why does this happen Batching HeadachesThis is where we run head first into the problems with React s batch updating of state variables React sees that we re setting showProcessing to true near the beginning of runSlowProcess but we re also setting it to false near the end of the process So the batched result is that it simply sets showProcessing to false Of course it was already false when we began the process So setting the previous value of false to false results in the user never even seeing the in progress interstitial Even if we solved that problem the user would never see any of the percent updates to the progress variable displayed inside the lt CircularProgress gt component Why Because React sees that the state variable progress is being updated repeatedly through the outer for loop Thus it batches all of those updates into a single value Of course this completely undermines the whole purpose of having a progress indicator in the first place Frustrating Non HelpRemember the lt CircularProgress gt component comes from Material UI And Material UI has a ton of helpful documentation that s supposed to show you how to use their components So my first step was to go back to that documentation for help But it was of no help whatsoever Here s the code sample that Material UI gives you to illustrate how you can update the progress value in the lt CircularProgress gt component export default function CircularDeterminate const progress setProgress React useState useEffect gt const timer setInterval gt setProgress prevProgress gt prevProgress gt prevProgress return gt clearInterval timer return lt CircularProgress variant determinate value progress gt To be clear Material UI s code sample works I mean it does dynamically update the progress value inside the lt CircularProgress gt component But this is one of the few times that I found their documentation to be borderline useless You see they re using useEffect in conjunction with setInterval to blindly update the progress value based on nothing more than a predetermined delay of milliseconds While that works fine for displaying a rote example of how the component renders it does nothing to tell us how we can tie the progress value to an actual meaningful calculation based upon the true progress of the process Faced with this very useless example I then did what any lifelong developer would do I started googling But almost all of the posts I found on places like Stack Overflow were similarly useless The issue you encounter when you google this problem is that nearly every developer has the exact same answer Don t update React state variables in a loop While I understand that there are many scenarios where you do want to avoid repeatedly updating React state inside a loop the simple fact is that this use case is the quintessential use case where you absolutely should be updating React state inside a loop Because the progress value should ideally be calculated based upon the actual progress of the algorithm NOT based upon some mindless setInterval delay I actually encounter this sort of non help all the time You re trying to solve some kind of sticky programming problem But rather than providing any meaningful help the mouth breathers simply reply that you shouldn t be doing this at all It s like seeing someone s post about how they can t figure out how to cook a proper souffle without it collapsing and becoming a mess and some smartass troll in the cooking forum responds by saying You shouldn t be cooking souffles anyway Just make an omelette Wow That s sooooo helpful Thankfully I did eventually solve the problem Promises To The RescueThe key to solving this one is that you have to introduce a delay If you look at what s happening in Material UI s example they re invoking a delay with setInterval But the real reason why their example works is because the setInterval is embedded within useEffect This creates a kind of feedback loop where the state variable is updated inside useEffect then the reconciliation process updates the DOM which triggers another call to useEffect which then updates the variable again and so on and so on Of course in my example I m trying to track the progress of a function inside a Hook So it s not terribly useful to rely upon useEffect But there s another way to invoke a delay without using useTimeout or useInterval You can use a promise Promises and their associated async await convention basically knock React out of its batch update mentality The updated useSlowProcess code looks like this useSlowProcess jsexport const useSlowProcess gt const appState useContext AppState const runSlowProcess async gt const startTime Math round Date now appState setProgress appState setShowProcessing true const delay gt new Promise resolve gt setTimeout resolve for let i i lt i for let j j lt j for let k k lt k for let l l lt l do the stuffs console log i appState setProgress i await delay appState setShowProcessing false console log Elapsed time Math round Date now startTime seconds return runSlowProcess Now when you click the START SLOW PROCESS button the progress interstitial shows up on the screen including the lt CircularProgress gt component with it s constantly updated progress indicator Notice a few things about this approach I invoke the delay directly after I ve updated the progress value inside the for loop This has the side effect of knocking React out of the batch update process The length of the delay is mostly immaterial As you can see I m invoking a delay of only milliseconds That may not seem like much but it s enough to trigger DOM updates in React ConclusionI just wanna be clear that in the vast majority of instances it s truly a solid idea to avoid doing repeated React state updates inside a loop But I wanted to highlight this use case because when you re trying to give the user real time info on the status of an ongoing process it s one potential scenario where it makes total sense to do it 2023-04-24 21:57:28
海外TECH DEV Community Mock imported modules in Jest https://dev.to/rafaf/mock-imported-modules-in-jest-26ng Mock imported modules in JestWhen working with JavaScript it s so common to import external or internal libraries Sometimes in order to implement modularity and reusability in our project sometimes to avoid implementing features that have been already developed by a third party Today we re gonna see how to mock these libraries when testing the code are using them with Jest suite First of all let s suppose we have the following code maths jsexport const sum a b gt a bexport const substract a b gt a b appimport sum substract from math mjs const sumResult sum const substractResult substract Given that code we could have two scenarios Mock the full import i e the full library Mock only one of the methods but keep the original code of the other oneSo let s see each case Mocking the full libraryTo mock the full library we just need to mock one of the method the other one will remain undefined or we can mock all the methods The mocking technique is indifferent it depends on what are we testing mock only one methodjest mock math gt sum jest fn mock only one method with implementation jest mock math gt sum jest fn mockImplementation gt mock all methodsjest mock math gt sum jest fn substract jest fn Mocking only one of the imported methodsAs we said before we can import only one of the methods and keep the original implementation for the rest of the methodsIn the following example we are mocking the substrack method but keep the original implementation of the rest of the library in this case the add methodjest mock math gt const originalMathLib jest requireActual math return originalMathLib substract jest fn It s very important to include this code at the very top of our testing file before any other import These mocks MUST be the firsts lines of our file 2023-04-24 21:01:33
ニュース BBC News - Home New Sudan ceasefire announced but doubts remain https://www.bbc.co.uk/news/world-africa-65380154?at_medium=RSS&at_campaign=KARANGA moves 2023-04-24 21:37:42
ニュース BBC News - Home Sudan: UK sends military team as it weighs evacuation options https://www.bbc.co.uk/news/uk-65378185?at_medium=RSS&at_campaign=KARANGA evacuation 2023-04-24 21:07:47
ニュース BBC News - Home NFL: Aaron Rodgers to join New York Jets after trade deal agreed with Green Bay Packers https://www.bbc.co.uk/sport/american-football/65381873?at_medium=RSS&at_campaign=KARANGA NFL Aaron Rodgers to join New York Jets after trade deal agreed with Green Bay PackersVeteran quarterback Aaron Rodgers will join the New York Jets after they agree a trade deal with the Green Bay Packers 2023-04-24 21:52:41
ニュース BBC News - Home Luton Town 2-1 Middlesbrough: Carlton Morris' controversial penalty wins it for Hatters https://www.bbc.co.uk/sport/football/65295695?at_medium=RSS&at_campaign=KARANGA Luton Town Middlesbrough Carlton Morris x controversial penalty wins it for HattersCarlton Morris controversial second half penalty gives Luton a comeback win over Championship play off rivals Middlesbrough 2023-04-24 21:21:06

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)