投稿時間:2022-03-22 12:25:03 RSSフィード2022-03-22 12:00 分まとめ(32件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT InfoQ AWS Backup for AmazonS3が一般提供へ https://www.infoq.com/jp/news/2022/03/aws-backup-s3/?utm_campaign=infoq_content&utm_source=infoq&utm_medium=feed&utm_term=global AWSBackupforAmazonSが一般提供へAmazonは最近、AWSBackupforAmazonSの一般提供を発表した。 2022-03-22 02:01:00
TECH Engadget Japanese 第3世代iPhone SE分解動画が公開。バッテリー容量は第2世代より大きく https://japanese.engadget.com/third-gen-iphone-se-teardown-larger-battery-021555324.html iphonese 2022-03-22 02:15:55
IT ITmedia 総合記事一覧 [ITmedia News] 自治体から迷惑メール91万件 SBテクノロジーのセキュリティクラウド、設定ミス突かれ踏み台に https://www.itmedia.co.jp/news/articles/2203/22/news096.html itmedia 2022-03-22 11:49:00
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 大阪市の「うめきた外庭SQUARE」で実験続々 パナは“みどり×スポーツ” https://www.itmedia.co.jp/business/articles/2203/22/news086.html itmedia 2022-03-22 11:35:00
IT ITmedia 総合記事一覧 [ITmedia News] Google Forms APIが正式リリース  Googleフォームの作成や編集、集計をプログラミングで制御可能に https://www.itmedia.co.jp/news/articles/2203/22/news091.html google 2022-03-22 11:10:00
TECH Techable(テッカブル) ファッション性にも注目! 春からの新生活を豊かにする必携スマートリング4選 https://techable.jp/archives/175508 電子決済 2022-03-22 02:00:13
AWS AWS Japan Blog 新規/アップデートされた AWS Well-Architected レンズ https://aws.amazon.com/jp/blogs/news/new-and-updated-aws-well-architected-lenses/ 新しい年に向けて新しいワークロードを計画している場合は、AWSのベストプラクティスの実装に関するガイドとして、新しいレンズと更新されたレンズをぜひご確認ください。 2022-03-22 02:55:52
js JavaScriptタグが付けられた新着投稿 - Qiita Phaser.jsでCPU対戦ポーカーを作りました https://qiita.com/doumeishi/items/8595e6e85e2b20323c76 phaser 2022-03-22 11:13:33
Ruby Rubyタグが付けられた新着投稿 - Qiita 【LeetCode】20. Valid Parenthesesを解いてみた https://qiita.com/kazuki-ayimon/items/8a1f54b9c374e1f42467 問題文を和訳文字、、、、およびのみを含む文字列sを指定して、入力文字列が有効かどうかを判断します。 2022-03-22 11:33:22
Ruby Rubyタグが付けられた新着投稿 - Qiita 【LeetCode】14. Longest Common Prefixを解いてみた https://qiita.com/kazuki-ayimon/items/15baa38261c4a1201da1 【LeetCode】LongestCommonPrefixを解いてみたはじめにコーディングテスト対策としてLeetCodeのLongestCommonPrefixを解いていく。 2022-03-22 11:28:04
Linux Ubuntuタグが付けられた新着投稿 - Qiita aptでインストール済のパッケージ数を色々と確認してみる https://qiita.com/pyon_kiti_jp/items/1284653030bd93de7610 aptlistinstalledgrepvListingwclさらに、このコマンドでも、件が検索されるだろうと期待して実行してみると、結果は件aptlistgrepinstalledwclインストール済みのパッケージで、かつ、更新可能なパッケージには、installedではなく、upgradableがついているようです。 2022-03-22 11:18:09
Docker dockerタグが付けられた新着投稿 - Qiita 遅いDocker for macを「Mutagen compose」で爆速にする(M1対応) https://qiita.com/JO95/items/15d01956ebf0b83fbdc4 起動されたかどうか確認dockerpswebdbmutagenコンテナのつが起動していれば成功Volumeの確認dockervolumelsgrepmutagenvolumelocalmutagenvolume起動が確認できたら、ローカル環境にアクセスしたり、ファイルが問題なく同期されるかを試すとデフォルトのDockerformacとの違いを体感できると思います。 2022-03-22 11:04:05
技術ブログ Developers.IO ALBでClient TLS Negotiation Errorが発生している際にAWS側から情報を得る方法について考えてみた https://dev.classmethod.jp/articles/alb_client_tls_negotiation_error_identify/ clienttlsnegotiationerror 2022-03-22 02:34:42
技術ブログ Developers.IO Organizations連携を使って組織内のAmazon Inspectorを有効化してみる https://dev.classmethod.jp/articles/organizations-inspector-all-account/ amazoninspector 2022-03-22 02:33:14
技術ブログ Developers.IO WireGuardベースのTailscaleを使ってAmazon Lightsail上にVPNサーバを10分で作る https://dev.classmethod.jp/articles/launch-tailscale-vpn-on-amazon-lightsail-in-1-min/ tailscale 2022-03-22 02:06:21
海外TECH DEV Community User notifications with Rails, Noticed, and Hotwire https://dev.to/davidcolbyatx/user-notifications-with-rails-noticed-and-hotwire-39ga User notifications with Rails Noticed and HotwireA nearly universal need in web applications is user notifications An event happens in the application that the user cares about and you inform the user of the event A common example is in applications that have a commenting system ーwhen a user mentions another user in a comment the application notifies the mentioned user of that comment through email The channel s used to notify users of new important events depends on the application but the path very often includes an in app notification widget that shows the user their latest notifications Other common options include emails text messages Slack and Discord Rails developers that need to add a notification system to their application often turn to Noticed Noticed is a gem that makes it easy to add new multi channel notifications to Rails applications Today we are going to take a look at how Noticed works by using Noticed to implement in app user notifications We will send those notifications to logged in users in real time with Turbo Streams and for extra fun we will load user notifications inside of a Turbo Frame When we are finished our application will work like this Before we begin this tutorial assumes that you are comfortable building simple Ruby on Rails applications independently No prior knowledge of Turbo or Noticed is required Let s dive in Application setupTo follow along with this tutorial start by cloning this repository from Github and then set it up cd user noticesbin setupThe starter repo contains a Rails application with Turbo Tailwind and Devise ready to go The starter repo uses Ruby but everything in this tutorial will work fine with Ruby and if you prefer If you want to work from your own application instead of cloning the starter you will need a Rails application with Turbo installed and an authentication system built around a User model When you re ready to start building start the server and build Tailwind s css with bin dev Noticed setupOur starter application comes with a Devise powered user model and the root path set to the Dashboard show action which just contains links to sign in or sign out for now Before diving in to the code create at least one user through the form at http localhost users sign up so that you can login and test notifications later in this tutorial Eventually our users will be able to create Messages for other users in the application Each time a message is a created a new Notification will be created and the user the message is for will see that notification on their dashboard Before any of that can happen we need to add Noticed to our application and scaffold a Message resource Start by adding Noticed from your terminal bundle add noticedrails generate noticed modelrails db migrateThese commands are straight from the Noticed installation docs If your Rails app is running be sure to restart it after adding the Noticed gem to your Gemfile with bundle add Next update app models user rb to associate notifications with users class User lt ApplicationRecord devise database authenticatable registerable recoverable rememberable validatable has many notifications as recipientendHere we added the notifications has many association as directed by the Noticed setup script Now our users can receive notifications but we don t have anything useful to notify them about We will fix that by scaffolding a Message resource From your terminal rails g scaffold message content text user referencesrails db migrateThanks to the magic of Rails the scaffold generator gives us almost everything we need to start creating messages and associating them with users Because we are using Tailwind via the tailwindcss rails gem the scaffold generator also includes some nice looking base styles too After the generator runs update the User model again at app models user rb class User lt ApplicationRecord devise database authenticatable registerable recoverable rememberable validatable has many messages has many notifications as recipientendHere we added has many messages to set up the other side of the messages relationship For convenience we can also add a link to the messages index page in app views dashboard show html erb lt div gt lt if user signed in gt Signed in as lt current user email gt lt button to Sign out destroy user session path method delete class text blue gt lt link to All messages messages path class text blue gt lt else gt lt link to Sign in new user session path class text blue gt lt end gt lt div gt And then make a small adjustment to the messages form so we don t have to memorize user ids lt form with model message class contents do form gt lt if message errors any gt lt div id error explanation class bg red text red px py font medium rounded lg mt gt lt h gt lt pluralize message errors count error gt prohibited this message from being saved lt h gt lt ul gt lt message errors each do error gt lt li gt lt error full message gt lt li gt lt end gt lt ul gt lt div gt lt end gt lt div class my gt lt form label content gt lt form text area content rows class block shadow rounded md border border gray outline none px py mt w full gt lt div gt lt div class my gt lt form label user id gt lt form select user id options for select User all pluck email id class block shadow rounded md border border gray outline none px py mt w full gt lt div gt lt div class inline gt lt form submit class rounded lg py px bg blue text white inline block font medium cursor pointer gt lt div gt lt end gt With these changes in place head to http localhost messages and create a couple of messages to ensure that creating messages works as expected Now that we have Noticed installed and messages ready to go next up we will send users notifications when a new message is created Message notificationsOur goal in this section is to create and display notifications to logged in users on the Dashboard show page Step one is to add a new notification using the the generator built in to Noticed From your terminal rails generate noticed notification MessageNotificationThis generator creates a new MessageNotification class at app notifications message notification rb Head there next and make a few small updates class MessageNotification lt Noticed Base deliver by database param message def message params message content end def url message path params message endendHere deliver by database stores the newly created notification in the database which will be important for Turbo Stream broadcasts later If we wanted to send the notification by email too we could add deliver by email mailer SomeMailer as described in the Noticed docs param message serializes the message object and stores it with the notification record in the database We use that serialized message in the message and url methods Serializing objects into params in this manner makes it easy to access records related to the notification without managing complex references ーjust dump the record s you need into params and profit We can now use our MessageNotification to send notifications to users when a new message is created Next we need to put the MessageNotification class into use Head to app models message rb and update it class Message lt ApplicationRecord has noticed notifications belongs to user after create commit notify user def notify user MessageNotification with message self deliver later user endendEach time a message is created after create commit notify user runs and creates a new MessageNotification serializing the message object and delivering the message to the message s user We also add has noticed notifications to ensure that when a message is destroyed any related notifications are destroyed too With those small changes we now have a database backed notification system up and running Neat We have notifications in the database now but there is no way for users to see those notifications anywhere which is not very useful Next up we will create a Notifications controller to display notifications to users From your terminal generate the controller and a partial to render each notification rails g controller Notifications indextouch app views notifications notification html erbHead to config routes rb and add a notifications path helper Rails application routes draw do resources notifications only index resources messages devise for users get dashboard show root dashboard show endUpdate the NotificationsController at app controllers notifications controller rb class NotificationsController lt ApplicationController def index notifications Notification where recipient current user endendHere we scope notifications to the current user so users only see their own notifications when logged in to the application Update the new Notifications index view at app views notifications index html erb lt turbo frame tag notifications do gt lt h class font bold text xl gt Notifications lt h gt lt ul gt lt render notifications gt lt ul gt lt end gt Note the turbo frame tag wrapping the list of notifications Our plan is to render the list of notifications on the dashboard show page ーwe will use Turbo Frame s eager loading functionality to load the content of the notifications index page on the dashboard show page render notifications relies on Rails collection rendering to render each notification Before this will work we need to fill in app views notifications notification html erb lt li gt lt div gt lt p class text gray gt lt notification to notification message gt lt p gt lt div class flex justify between mt text gray text sm space x gt lt p gt Received on lt notification created at to date gt lt p gt lt p gt Status lt notification read Read Unread gt lt p gt lt div gt lt div gt lt li gt Here we use to notification from Noticed to access the message method we added in MessageNotification earlier and use the built in read method from Noticed to check if the user has read the notification or not One last step here before users can see notifications on the dashboard Head to app views dashboard show html erb and update it to add an eager loaded Turbo Frame for logged in users lt div class flex justify between gt lt if user signed in gt lt div gt Signed in as lt current user email gt lt button to Sign out destroy user session path method delete class text blue gt lt link to All messages messages path class text blue gt lt div gt lt turbo frame tag notifications src notifications path gt lt else gt lt link to Sign in new user session path class text blue gt lt end gt lt div gt The turbo frame tag has an id of notifications which matches the Turbo Frame rendered by Notifications index When Turbo eager loads content for a Turbo Frame it expects the url passed to src to return a response that includes a Turbo Frame with a matching id The sequence of events for our eager loaded notifications index page is this A logged in user visits Dashboard showDashboard show is loadedTurbo sees the turbo frame tag with an src attribute and initiates a new request to notificationsNotifications index returns HTML that includes a turbo frame tag that matches the tag that initiated the requestTurbo extracts the contents of the turbo frame tag and uses that content to replace the content of the existing Turbo FrameAt this point logged in users can see their notifications on the dashboard Test it out by logging in as a user and then creating a new messages for that user Refresh the dashboard as that user and see that your notifications are listed on the dashboard While our users can see notifications they don t see those notifications in real time ーthey have to manually refresh the dashboard before they see new notifications Let s wrap up this tutorial by making notifications real time with Turbo Stream broadcasts Real time notifications with Turbo StreamsTurbo model broadcasts powered by turbo rails make it easy to send real time updates to users with ActionCable When we finish this section each time a new notification is created a Turbo Stream broadcast will be sent over an ActionCable channel that will automatically insert new notifications for a user into the user s dashboard notifications list To start update app models notification rb to trigger a Turbo Stream broadcast when a new notification is created class Notification lt ApplicationRecord include Noticed Model belongs to recipient polymorphic true after create commit broadcast to recipient def broadcast to recipient broadcast append later to recipient notifications target notifications list partial notifications notification locals notification self endendHere the broadcast to recipient method appends a new notification to the list of notifications To ensure that only the user the notification is for receives the broadcast we set the broadcast channel to recipient notifications as described in the turbo rails source The model update handles sending Turbo Stream broadcasts but before the broadcast will be picked up by the front end we need to subscribe users to a Turbo Stream channel We also must ensure the markup includes a notifications list id matching the target passed to broadcast append later to for the Turbo Stream to update Starting in app views notifications index html erb add the notifications list id to the ul containing the list of notifications lt turbo frame tag notifications do gt lt h class font bold text xl gt Notifications lt h gt lt ul id notifications list gt lt render notifications gt lt ul gt lt end gt And then in app views dashboard show html erb lt div class flex justify between gt lt if user signed in gt lt div gt Signed in as lt current user email gt lt button to Sign out destroy user session path method delete class text blue gt lt link to All messages messages path class text blue gt lt div gt lt turbo stream from current user notifications gt lt turbo frame tag notifications src notifications path gt lt else gt lt link to Sign in new user session path class text blue gt lt end gt lt div gt Here the turbo stream from helper from turbo rails subscribes the user to a channel that matches the channel our model is broadcasting from current user notifications in the view recipient notifications in the model When a user visits the dashboard the turbo stream from helper opens an ActionCable subscription to the matching channel Broadcasts to that channel are picked up by Turbo and used to update the page when new broadcasts are received The scoping of the channel to the current user ensures that users do not receive broadcasts intended for another user so that our new message notifications are only sent to the user the message is for With these changes in place login as a user in one browser and head to the dashboard Confirm the ActionCable channel subscription is created by checking the server logs for a line that looks like this Turbo StreamsChannel is streaming from ZlkOivdXNlciubRpYVzLVzZXIvMQ notificationsIn another browser head to the new messages form and create a message setting the user on the form to the user that you are logged in as in the first browser If all has gone well the new notification will be added to the list instantly with no page updates required Great work following along with this tutorial that is all of the code for the day Wrapping up amp further readingToday we built a simple notification system with Rails and Noticed and we used Turbo to display new notifications for users in real time Noticed is an extremely powerful gem that makes the work of building and expanding a multi channel notification system in a Rails app much simpler and the easy integration with Turbo Streams makes it a great match for any modern Rails application In our tutorial application we displayed notifications as a static list of every notification the user has ever received with no way to interact with them or remove them from the list We also required users to be on their dashboard to see the new notification In a production application we might expand our Notifications controller to include an update method that allows users to mark notifications as read and clear those notifications from the list We would would also likely build a notification indicator in the main navigation that is rendered on every page of our application with an icon indicating unread notifications think the ubiquitous bell icon seen across thousands of web applications The neat thing about this tutorial s approach is that the basic approach remains the same even for a more sophisticated implementation Use Turbo Streams to broadcast new notifications to users and update the UI in real time Use built in Noticed methods to act on notifications like mark as read to read a notification Use a Turbo Frame to fetch notifications for a user and load those notifications into a section of a larger page For further learning on Noticed Turbo Streams and Turbo Frames Check out the GoRails tutorial on Noticed Chris from GoRails wrote Noticed thanks Chris Read the simple but effective Noticed docs starting in the repo s readme and digging in to specific delivery methods as neededSolidify Turbo concepts with my Turbo article and my Turbo Frames and Turbo Streams on Rails articles for more on how to use Turbo with RailsFinally if you want to dig deeper into implementing notifications in a Rails application a chapter of my book is dedicated to building a very light notification system from scratch with inspiration from Noticed In the book we add real time updates in a more realistic way with the standard bell icon pop out notification list and the ability to mark notifications as read with a click The book is written in this same step by step tutorial style and covers building a modern Rails application from scratch with StimulusReflex CableReady Hotwire and friends Building your own notification system is a great exercise if you want to use Noticed in a real production application later since you will have a much greater understanding of and appreciation for what Noticed offers you That s all for today As always thanks for reading 2022-03-22 02:36:31
海外TECH DEV Community The JavaScript Skills You Need For React https://dev.to/sananayab/the-javascript-skills-you-need-for-react-4can The JavaScript Skills You Need For ReactOne of the most important things to understand about React is that it is fundamentally JavaScript This means that the better you are at JavaScript the more successful you will be with React Let s break down the essential concepts that you should know about JavaScript to master React And when I say these concepts are essential I mean that they are used in every single application that a React developer makes with little to no exceptions Learning these concepts is one of the most valuable things you can do to accelerate your ability to make React projects and become a skilled React developer so let s get started Function Declarations and Arrow FunctionsThe basis of any React application is the component In React components are defined with both JavaScript functions and classes But unlike JavaScript functions React components return JSX elements that are used to structure our application interface JavaScript function returns any valid JavaScript typefunction javascriptFunction return Hello world React function component returns JSXfunction ReactComponent props return lt h gt props content lt h gt Note the different casing between the names of JavaScript functions and React function components JavaScript functions are named in camel casing while React function components are written with pascal casing in which all words are capitalized There are two different ways to write a function in JavaScript the traditional way using the function keyword called a function declaration and as an arrow function which was introduced in ES Both function declarations and arrow functions can be used to write function components in React The primary benefit of arrow functions is their succinctness We can use several shorthands in order to write our functions to remove unnecessary boilerplate such that we can even write it all on a single line Function declaration syntaxfunction MyComponent props return lt div gt props content lt div gt Arrow function syntaxconst MyComponent props gt return lt div gt props content lt div gt Arrow function syntax shorthand const MyComponent props gt lt div gt props content lt div gt In the last example we are using several shorthands that arrow functions allow No parentheses around a single parameter Implicit return as compared to using the return keyword No curly braces for function body One small benefit of using function declarations over arrow functions is that you don t have to worry about problems with hoisting Due to the JavaScript behavior of hoisting you can use multiple function components made with function declarations in a single file in whichever order you like Function components made with arrow functions however cannot be ordered whichever way you like Because JavaScript variables are hoisted arrow function components must be declared before they are used function App return lt gt Valid FunctionDeclaration is hoisted lt FunctionDeclaration gt Invalid ArrowFunction is NOT hoisted Therefore it must be declared before it is used lt ArrowFunction gt lt gt function FunctionDeclaration return lt div gt Hello React lt div gt function ArrowFunction return lt div gt Hello React again lt div gt Another small difference in using the function declaration syntax is that you can immediately export a component from a file using export default or export before the function is declared You can only use the export keyword before arrow functions default exports must be placed on a line below the component Function declaration syntax can be immediately exported with export default or exportexport default function App return lt div gt Hello React lt div gt Arrow function syntax must use export onlyexport const App gt return lt div gt Hello React lt div gt Template LiteralsJavaScript has a clumsy history of working with strings particularly if you want to concatenate or connect multiple strings together Before the arrival of ES to add strings together you needed to use the operator to add each string segment to one another With the addition of ES we were given a newer form of string called a template literal which consists of two back ticks instead of single or double quotes Instead of having to use the operator we can connect strings by putting a JavaScript expression such as a variable within a special syntax Concatenating strings prior to ES Notice the awkward space after the word Hello function sayHello text return Hello text sayHello React Hello React Concatenating strings using template literals See how much more readable and predictable this code is function sayHelloAgain text return Hello again text sayHelloAgain React Hello again React What s powerful about template literals is their ability to use any JavaScript expression that is anything in JavaScript that resolves to a value within the syntax We can even include conditional logic using the ternary operator which is perfect for conditionally adding or removing a class or style rule to a given JSX element Go to react new and paste this code in to see it work import React from react function App const isRedColor setRedColor React useState false const toggleColor gt setRedColor prev gt prev return lt button onClick toggleColor style background isRedColor red black color white gt Button is isRedColor red not red lt button gt export default App In short template literals are great for React whenever we need to dynamically create strings For example when we use string values that can change in our head or body elements in our site import React from react import Head from Head function Layout props Shows site name i e Reed Barger at end of page title const title props title Reed Barger return lt gt lt Head gt lt title gt title lt title gt lt Head gt lt main gt props children lt main gt lt gt Short Conditionals amp amp Ternary OperatorConsidering that React is just JavaScript it is very easy to conditionally show or hide JSX elements using simple if statements and sometimes switch statements import React from react function App const isLoggedIn true if isLoggedIn Shows Welcome back return lt div gt Welcome back lt div gt return lt div gt Who are you lt div gt export default App With the help of some essential JavaScript operators we cut down on repetition and make our code more concise We can transform the if statement above into the following using the ternary operator The ternary operator functions exactly the same as an if statement but it is shorter it is an expression not a statement and can be inserted within JSX import React from react function App const isLoggedIn true Shows Welcome back return isLoggedIn lt div gt Welcome back lt div gt lt div gt Who are you lt div gt export default App Ternary operators can also be used inside curly braces again since it is an expression import React from react function App const isLoggedIn true Shows Welcome back return lt div gt isLoggedIn Welcome back Who are you lt div gt export default App If we were to change the example above and only wanted to show text if the user was logged in if isLoggedIn is true this would be a great use case for the amp amp and operator If the first value operand in the conditional is true the amp amp operator displays the second operand Otherwise it returns the first operand And since it is falsy is a value automatically converted to the boolean false by JavaScript it is not rendered by JSX import React from react function App const isLoggedIn true If true Welcome back if false nothing return lt div gt isLoggedIn amp amp Welcome back lt div gt export default App Let s say that we want the reverse of what we re doing now to only say Who are you if isLoggedIn is false If it s true we won t show anything For this logic we can use the or operator It essentially works opposite to the amp amp operator If the first operand is true the first falsy operand is returned If the first operand is false the second operand is returned import React from react function App const isLoggedIn true If true nothing if false Who are you return lt div gt isLoggedIn Who are you lt div gt export default App Three Array Methods map filter reduce Inserting primitive values into JSX elements is easy just use curly braces We can insert any valid expressions including variables that contain primitive values strings numbers booleans and so on as well as object properties that contain primitive values import React from react function App const name Reed const bio age isEnglishSpeaker true return lt gt lt h gt name lt h gt lt h gt I am bio age years old lt h gt lt p gt Speaks English bio isEnglishSpeaker lt p gt lt gt export default App What if we have an array and we want to iterate over that array to show each array element within an individual JSX element For this we can use the map method It allows us to transform each element in our array in the way we specify with the inner function Note that it is especially concise when used in combination with an arrow function Note that this isn t exactly the same as the normal JavaScript map method but is very similar import React from react function App const programmers Reed John Jane return lt ul gt programmers map programmer gt lt li gt programmer lt li gt lt ul gt export default App There are other flavors of the map method that perform related tasks and are important to know because they can be chained in combination with one another Why Because map like many array methods returns a shallow copy of the array that it has iterated over This enables its returned array to be passed onto the next method in the chain filter as its name indicates allows us to filter certain elements out of our array For example if we wanted to remove all names of programmers that started with J we could do so with filter import React from react function App const programmers Reed John Jane return lt ul gt Returns Reed programmers filter programmer gt programmer startsWith J map programmer gt lt li gt programmer lt li gt lt ul gt export default App It s important to understand that both map and filter are just different variations of the reduce array method which is capable of transforming array values into virtually any data type even non array values Here s reduce performing the same operation as our filter method above import React from react function App const programmers Reed John Jane return lt ul gt Returns Reed programmers reduce acc programmer gt if programmer startsWith J return acc concat programmer else return acc map programmer gt lt li gt programmer lt li gt lt ul gt export default App Object Tricks Property Shorthand Destructuring Spread OperatorLike arrays objects are a data structure that you need to be comfortable with when using React Since objects exist for the sake of organized key value storage unlike arrays you re going to need to be very comfortable accessing and manipulating object properties To add properties to an object as you create it you name the property and its corresponding value One very simple shorthand to remember is that if the property name is the same as the value you only have to list the property name This is the object property shorthand const name Reed const user instead of name name we can use name console log user name ReedThe standard way to access properties from an object is using the dot notation An even more convenient approach however is object destructuring It allows us to extract properties as individual variables of the same name from a given object It looks somewhat like you re writing an object in reverse which is what makes the process intuitive It s much nicer to use than having to use the object name multiple times to access each time you want to grab a value from it const user name Reed age isEnglishSpeaker true Dot property accessconst name user name const age user age Object destructuringconst age name isEnglishSpeaker knowsEnglish user Use to rename a value as you destructure itconsole log knowsEnglish trueNow if you want to create objects from existing ones you could list properties one by one but that can get very repetitive Instead of copying properties manually you can spread all of an object s properties into another object as you create it using the object spread operator const user name Reed age isEnglishSpeaker true const firstUser name user name age user age isEnglishSpeaker user isEnglishSpeaker Copy all of user s properties into secondUser const secondUser user What is great about the object spread is that you can spread in as many objects into a new one as you like and you can order them like properties But be aware that properties that come later with the same name will overwrite previous properties const user name Reed age const moreUserInfo age country USA Copy all of user s properties into secondUser const secondUser user moreUserInfo computer MacBook Pro console log secondUser name Reed age country USA computer Macbook Pro Promises Async Await SyntaxVirtually every React application consists of asynchronous code code that takes an indefinite amount of time to be executed Particularly if you need to get or change data from an external API using browser features like the Fetch API or the third party library axios Promises are used to resolve asynchronous code to make it resolve like normal synchronous code which we can read from top to bottom Promises traditionally use callbacks to resolve our asynchronous code We use the then callback to resolve successfully resolved promises while we use the catch callback to resolve promises that respond with an error Here is a real example of using React to fetch data from my GitHub API using the Fetch API to show my profile image The data is resolved using promises Go to react new and paste this code in to see it work import React from react const App gt const avatar setAvatar React useState React useEffect gt The first then lets us get JSON data from the response The second then gets the url to my avatar and puts it in state fetch then response gt response json then data gt setAvatar data avatar url catch error gt console error Error fetching data error return lt img src avatar alt Reed Barger gt export default App Instead of always needing to use callbacks to resolve our data from a promise we can use a cleaned syntax that looks identical to synchronous code called the async await syntax The async and await keywords are only used with functions normal JavaScript functions not React function components To use them we need to make sure our asynchronous code is in a function prepended with the keyword async Any promise s value can then be resolved by placing the keyword await before it Go to react new and paste this code in to see it work import React from react const App gt const avatar setAvatar React useState React useEffect gt Note that because the function passed to useEffect cannot be async we must create a separate function for our promise to be resolved in fetchAvatar async function fetchAvatar const response await fetch const data await response json setAvatar data avatar url fetchAvatar return lt img src avatar alt Reed Barger gt export default App We use the catch callback to handle errors within traditional promises but how do you catch errors with async await We still use catch and when we hit an error such as when we have a response from our API that is in the or status range Go to react new and paste this code in to see it work import React from react const App gt const avatar setAvatar React useState React useEffect gt async function fetchAvatar Using an invalid user to create a not found error const response await fetch if response ok const message An error has occured response status In development you ll see this error message displayed on your screen throw new Error message const data await response json setAvatar data avatar url fetchAvatar return lt img src avatar alt Reed Barger gt export default App ES Modules Import Export syntaxES gave us the ability to easily share code between our own JavaScript files as well as third party libraries using ES modules Also when we leverage tools like Webpack we can import assets like images and svgs as well as CSS files and use them as dynamic values in our code We re bringing into our file a library React a png image and CSS styles import React from react import logo from img site logo png import styles app css function App return lt div gt Welcome lt img src logo alt Site logo gt lt div gt export default App The idea behind ES modules is to be able to split up our JavaScript code into different files to make it modular or reusable across our app As far as JavaScript code goes we can import and export variables and functions There are two ways of importing and exporting as named imports exports and as default imports exports There can only be one thing we make a default import or export per file and we can make as many things named imports export as we like For example constants jsexport const name Reed export const age export default function getName return name app js Notice that named exports are imported between curly bracesimport getName name age from constants js console log name age getName We can also write all of the exports at the end of the file instead of next to each variable or function constants jsconst name Reed const age function getName return name export name age export default getName app jsimport getName name age from constants js console log name age getName You can also alias or rename what you are importing using the as keyword for named imports The benefit of default exports is that they can be named to whatever you like constants jsconst name Reed const age function getName return name export name age export default getName app jsimport getMyName name as myName age as myAge from constants js console log myName myAge getMyName 2022-03-22 02:23:11
海外TECH WIRED These Smart Glasses Want to Replace Your Laptop https://www.wired.com/story/nimo-planet-nimo-glasses screens 2022-03-22 02:30:00
金融 JPX マーケットニュース [東証]監理銘柄(確認中)の指定:東洋建設(株) https://www.jpx.co.jp/news/1023/20220322-11.html 東洋建設 2022-03-22 11:10:00
ニュース BBC News - Home Teenage girl on e-scooter dies in crash with van in east London https://www.bbc.co.uk/news/uk-england-london-60826567?at_medium=RSS&at_campaign=KARANGA driver 2022-03-22 02:25:01
ニュース BBC News - Home Police failing to bring in talent from black communities, says racism lead https://www.bbc.co.uk/news/uk-60826602?at_medium=RSS&at_campaign=KARANGA incidents 2022-03-22 02:00:57
北海道 北海道新聞 海自の新型護衛艦「くまの」就役 コンパクト船体で多様任務に対応 https://www.hokkaido-np.co.jp/article/659631/ 海上自衛隊 2022-03-22 11:24:00
北海道 北海道新聞 マリウポリの死者「3000人」 住宅8割破壊と当局者 https://www.hokkaido-np.co.jp/article/659622/ 破壊 2022-03-22 11:16:00
北海道 北海道新聞 元島民、怒りと落胆 「生きている間に島に行くことはできるのか」 ロシア平和条約交渉拒否 https://www.hokkaido-np.co.jp/article/659612/ 北方領土問題 2022-03-22 11:10:04
北海道 北海道新聞 <釧路>マリモ研究の第一人者 若菜勇さん(64) https://www.hokkaido-np.co.jp/article/659616/ 特別天然記念物 2022-03-22 11:05:00
北海道 北海道新聞 <美瑛>熊本から移住 美瑛町立病院の眼科医 谷原秀信さん(61) https://www.hokkaido-np.co.jp/article/659614/ 谷原 2022-03-22 11:02:00
北海道 北海道新聞 2カ月半ぶり、日常へ一歩 18都道府県でまん延防止解除 https://www.hokkaido-np.co.jp/article/659615/ 都道府県 2022-03-22 11:03:00
ビジネス 東洋経済オンライン 日本に「危機管理専門」の官僚が足りない根本理由 国民を危機から守るのに欠かせない2つの存在 | 政策 | 東洋経済オンライン https://toyokeizai.net/articles/-/539186?utm_source=rss&utm_medium=http&utm_campaign=link_back 危機管理 2022-03-22 12:00:00
IT 週刊アスキー 「千本桜の世界展-Be Here-」ところざわサクラタウンにて3月26日より開催 https://weekly.ascii.jp/elem/000/004/086/4086792/ behere 2022-03-22 11:30:00
IT 週刊アスキー 崎陽軒「ハマスタ☆応援弁当」3月25日よりプロ野球シーズン終了時まで、横浜スタジアムでのホームチーム試合開催日限定販売 https://weekly.ascii.jp/elem/000/004/086/4086796/ 横浜スタジアム 2022-03-22 11:30:00
マーケティング AdverTimes H2O食品グループ、マーケ統括部を新設(22年4月1日付) https://www.advertimes.com/20220322/article379562/ 食品 2022-03-22 02:01:51
海外TECH reddit Game Thread?? https://www.reddit.com/r/Predators/comments/tjsfi2/game_thread/ Game Thread Lauzon makes his debut Game day bot broken Anyways GO PREDS submitted by u ellisisbae to r Predators link comments 2022-03-22 02:13:24

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

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

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