投稿時間:2023-04-09 19:11:47 RSSフィード2023-04-09 19:00 分まとめ(11件)
カテゴリー等 | サイト名等 | 記事タイトル・トレンドワード等 | リンクURL | 頻出ワード・要約等/検索ボリューム | 登録日 |
---|---|---|---|---|---|
IT | 気になる、記になる… | C smart、オンラインストアでMacの全モデルを5,500円オフで販売するセールを開催中(4月30日まで) | https://taisy0.com/2023/04/09/170499.html | apple | 2023-04-09 09:50:05 |
TECH | Techable(テッカブル) | 重さはわずか60g!ペンのように扱える軽量電動ドライバーがクラファンで目標金額達成 | https://techable.jp/archives/202965 | dukae | 2023-04-09 09:00:07 |
Linux | Ubuntuタグが付けられた新着投稿 - Qiita | Azure/Ubuntu にインストールした postfix / dovecot を Maildir 対応にする | https://qiita.com/nanbuwks/items/10e6dd1224ce0c3f76af | dovecot | 2023-04-09 18:32:09 |
AWS | AWSタグが付けられた新着投稿 - Qiita | AWS API Gatewayを構築してみた | https://qiita.com/gama1234/items/7e661fc0cb0057cd2f56 | apigat | 2023-04-09 18:08:14 |
Docker | dockerタグが付けられた新着投稿 - Qiita | Docker Rails 7 x Mysql | https://qiita.com/kandalog/items/4b2b4a8f8f0fb78dbe3b | dockerco | 2023-04-09 18:26:02 |
Ruby | Railsタグが付けられた新着投稿 - Qiita | Docker Rails 7 x Mysql | https://qiita.com/kandalog/items/4b2b4a8f8f0fb78dbe3b | dockerco | 2023-04-09 18:26:02 |
技術ブログ | Developers.IO | API Gateway のカスタムアクセスログで EMF を使ってカスタムメトリクスを出力してみた | https://dev.classmethod.jp/articles/api-gateway-custom-accesslog-emf/ | amazonapigateway | 2023-04-09 09:08:15 |
技術ブログ | Developers.IO | ALB 리스너 규칙으로 고정 응답 반환 503 수정해 보기 | https://dev.classmethod.jp/articles/jw-alb-listener-rule-returns-fixed-response-503-try-modifying/ | ALB 리스너규칙으로고정응답반환 수정해보기안녕하세요클래스메소드김재욱 Kim Jaewook 입니다 이번에는ALB 리스너규칙으로고정응답반환을수정해보는과정을정리해봤습니다 HTTP 웹서버를구축함에있 | 2023-04-09 09:07:21 |
海外TECH | DEV Community | Authentication in React Applications using Firebase and its services. Part 3 | https://dev.to/dev_cody/authentication-in-react-applications-using-firebase-and-its-services-part-3-1j7o | Authentication in React Applications using Firebase and its services Part Logging the user inNow that we are done signing the user up and have signed the user out the next thing is to log the user back in Back to our Login component let s see how we can achieve this with firebase But first we have to add states to our inputs then start working on implementing the functionality import React useState from react import Box FormControl FormLabel Button Heading Text VStack Input useToast from chakra ui react import LoginCurve from iconsax react import app from firebaseConfig import getAuth signInWithEmailAndPassword from firebase auth import useNavigate from react router dom const Login gt initialise firebase auth const auth getAuth initialise toast component from chakra Ui const toast useToast initialise navigate from react router dom const navigate useNavigate states for each of the imputs const email setEmail useState const password setPassword useState const handleClick async gt if email amp amp password try await signInWithEmailAndPassword auth email password then cred gt toast title Login Successful description You have been logged in successfully status success duration isClosable true variant left accent position top right setEmail setPassword navigate profile catch error toast title Error description error message status error duration isClosable true variant left accent position top else toast title Error description Please fill in your details status error duration isClosable true variant left accent position top return lt Box mt gt lt VStack spacing gt lt Heading gt Login lt Heading gt lt Box maxW px gt lt FormControl gt lt VStack spacing gt lt Box gt lt FormLabel gt Email lt FormLabel gt lt Input type email placeholder Input your email fontSize px w px value email onChange e gt setEmail e target value gt lt Box gt lt Box gt lt FormLabel gt Password lt FormLabel gt lt Input type password placeholder Input your password fontSize px w px value password onChange e gt setPassword e target value gt lt Box gt lt Box gt lt Button type submit w px colorScheme teal onClick handleClick gt Login lt LoginCurve style marginLeft px gt lt Button gt lt Box gt lt VStack gt lt FormControl gt lt Box gt lt VStack gt lt Box gt export default LoginThe code above is the final code for the Login component after adding states to our inputs and writing the functionality Copy and paste the code in the code editor while we go through the codebase step by step Let s start with the imports I believe we are now familiar with almost all the imports except for the signInWithEmailAndPassword function What this function does is that it allows us to sign a user in with the email and password that have been provided earlier by the user during signup Then we called the function in the handleSubmit function If everything goes well the user will be logged in and then redirected to the profile page And if anything goes wrong the error toast will be displayed with the error message Retrieving the user s data from the firebase auth firestore database and firebase storageNow we have been able to sign users in with their email and password and we have been able to redirect them to the profile page so that each user can view his her profile but nothing is actually showing on the profile page how do we fix this We can do this in steps The first thing is to get the currently logged in user and from there we can get the user s email and the date the account was created The second step is to get the user s avatar from firebase storage The third and final step is to get the user s username and bio from firestore database import React useState useEffect from react import Box Avatar AvatarBadge Text Heading Stack Button useToast from chakra ui react import getAuth signOut from firebase auth import getFirestore query where getDocs collection from firebase firestore import getStorage ref getDownloadURL from firebase storage import Link useNavigate from react router dom import app from firebaseConfig const Profile gt const currentUser setCurrentUser useState null const userDetails setUserDetails useState const avatar setAvatar useState const auth getAuth const db getFirestore const storage getStorage const userRef collection db user data const navigate useNavigate const toast useToast const signout gt signOut auth then gt navigate login toast title Logout Successful description You have been logged out successfully status success duration isClosable true variant left accent position top right const getCurrentUser async gt try auth onAuthStateChanged user gt setCurrentUser user const q query userRef where user id user uid const avatarRef ref storage user uid if user getDownloadURL avatarRef then url gt setAvatar url getDocs q then async snapshot gt let user data snapshot docs map item gt user data push item data id item id return setUserDetails user data catch error toast title Error description error message status error duration isClosable true variant left accent position top right useEffect gt getCurrentUser const newDate currentUser metadata creationTime const date new Date newDate toDateString return lt gt currentUser lt Box maxW px mt bg gray p borderRadius boxShadow md display flex alignItems center justifyContent center mx auto gt lt Box gt lt Heading mb gt My Profile lt Heading gt lt Avatar bg teal size xl mb display block mx auto src avatar gt lt AvatarBadge boxSize em bg green gt lt Avatar gt lt Stack spacing fontWeight semibold gt lt Text gt Username userDetails user name lt Text gt lt Text gt Bio userDetails user bio lt Text gt lt Text gt Email currentUser email lt Text gt lt Text gt Date Joined date lt Text gt lt Stack gt lt Box textAlign center mt gt lt Button colorScheme teal onClick signout gt Logout lt Button gt lt Box gt lt Box gt lt Box gt lt Box mx auto mt gt lt Heading fontWeight semibold fontSize mb gt OOPS lt Heading gt lt Text mb gt You are not authorised to view this page please login to get acces lt Text gt lt Link to login gt lt Button gt Login lt Button gt lt Link gt lt Box gt lt gt export default ProfileWe should have a UI that looks like the picture below after pasting the code And that s it the code above is for the profile page once again it might look strange but let s go through it together Like I always do I will start from the imports at the top I know we are familiar with most of the things I imported so I will just go over the ones I haven t mentioned before So let s start with the firebase storage We imported getDownloadUrl from firebase storage what it is used for is to get an accessible URL of the image we uploaded to firebase storage because by default immediately after we uploaded the image we have given a name to it but we can only access the image in our firebase console and not anywhere else The next thing is the firebase firestore we imported the query function and where function which would be used to query the firestore database based on some conditions A concept in firestore database that I won t go deep into is firestore queries What are firestore queries Firestore queries are a way to retrieve data from a Firestore database in a specific way Firestore is a NoSQL document database that stores data in documents and collections and queries can be used to retrieve documents from collections based on specified conditions Firestore queries can filter documents based on specific conditions sort documents based on one or more fields limit the number of documents returned and retrieve only specific fields from each document Queries can also be combined to create more complex queries Firestore supports two types of queries simple queries and complex queries Simple queries are queries that use a single filter condition while complex queries use multiple filter conditions or multiple sorting or limiting conditions Firestore queries can be executed on the client side such as in mobile or web applications or on the server side using Cloud Functions or other server side technologies So I believe we have a little knowledge about firestore queries and how they work now so let s go back to our code Another thing we imported was the getDocs function which is used to get all the documents in a firestore collection The next thing we did was create states for the avatar the user details and the current user After that I initialized all the functions we imported from firebase Up next is the signout function we created and attached to a button to sign users out when it is clicked and then redirect them to the login page The next and most important thing is to get the user s data from firebase Once we initialized the getAuth function we have access to the onAuthStateChanged function which helps us to keep track of the authentication state of the user either currently logged in or not and from that we have access to the user object which gives us all the details about the currently logged in user and then we pass the user object to the setCurrentUser function The next thing is to use the firestore queries to get the currently logged in user s details The query function takes in two arguments the userRef and the where function in the where function we pass in our query condition and it goes thus We want firebase to go through all the documents in the collection and get us the document that has its user id key equal to the currently logged in user s id After that we created a reference for our avatar if we can still remember what we did earlier was that immediately after the user signs up and uploads his picture we changed the name of the image to the user s id The next code block checks if a user is present and if it is it should get us the download URL of the user s avatar After that we used the getDocs function and then pass in the query to get the user details We then use the then method to get the snapshot We created an empty array and set it to the user data variable After getting the snapshot we automatically have access to the docs method we then looped through it and after doing that we pushed the data into the empty array then pass the user data array into the setUserDetails function If we noticed in the snapshot docs method we pushed item data into the array and that s because the data we want that is coming from firebase is located in the data function We can check this out by console logging the item console log item We then called the function in a useEffect Wow guys we just built a simple full stack application with firebase that s so amazing thanks for following me throughout the project and also thanks for reading this article I hope to release another article soon ConclusionFirebase can be used to build full stack applications for both web and mobile in this article we demonstrated how to use different firebase features and services this is just a simple project and firebase has lots of features that can be used to build more complex applications Check out firebase docs to learn more | 2023-04-09 09:07:35 |
ニュース | BBC News - Home | Douglas Ross: Tories reject Scottish leader's Labour vote call | https://www.bbc.co.uk/news/uk-politics-65224008?at_medium=RSS&at_campaign=KARANGA | agenda | 2023-04-09 09:26:42 |
ニュース | BBC News - Home | Maia and Rina Dee named as British-Israeli sisters killed in West Bank shooting | https://www.bbc.co.uk/news/world-middle-east-65222234?at_medium=RSS&at_campaign=KARANGA | efrat | 2023-04-09 09:47:06 |
コメント
コメントを投稿