Тёмный

Use Axios with React Hooks for Async-Await Requests 

Dave Gray
Подписаться 319 тыс.
Просмотров 56 тыс.
50% 1

Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
Learn how to use Axios with React hooks for async / await requests. In this tutorial, we will create two custom React hooks with Axios. These Axios hooks will return both data and functions to help complete all CRUD operations.
💖 Support me on Patreon ➜ / davegray
⭐ Become a full-stack web dev with Zero To Mastery Courses:
- Advanced React: bit.ly/AdvReactDev
- Jr to Senior Web Dev Roadmap: bit.ly/WebDevRoadmap-JrtoSr
- Master FAANG Coding Interviews: bit.ly/FAANGInterview
🚩 Subscribe ➜ bit.ly/3nGHmNn
🚀 React JS for Beginners full course - 9 hours: • React JS Full Course f...
📬 Course Updates ➜ courses.davegray.codes/
🔗 Source Code: github.com/gitdagray/react_ho...
Use Axios with React Hooks for Async-Await Requests
(00:00) Intro
(00:41) Welcome
(00:54) Install Axios
(01:38) useAxios hook
(03:14) Request Config
(04:02) useAxios continued
(05:23) AbortController - not isMounted
(06:19) useAxios completed
(09:33) Create an Axios instance
(11:00) Joke component
(16:25) Testing useAxios
(16:52) Add refetch to useAxios
(19:49) Testing refetch
(20:13) useAxios vs useAxiosFunction
(20:54) useAxiosFunction
(25:08) Create a 2nd Axios instance
(25:43) Posts component
(33:45) Quick debug
(34:41) Testing useAxiosFunction
☕ Buy Me A Coffee: www.buymeacoffee.com/davegray
📚 Tutorial References:
Stop Checking If Your React Component is Mounted: / react-stop-checking-if...
Axios Request Config Docs: axios-http.com/docs/req_config
🔗 ES7 React JS Snippets Extension for VS Code:
marketplace.visualstudio.com/...
🔗 React Dev Tools Extension for Chrome:
chrome.google.com/webstore/de...
📚 General React References:
ReactJS Official site: reactjs.org/
React Wikipedia: en.wikipedia.org/wiki/React_(...)
React Jobs: www.ziprecruiter.com/candidat...
✅ Follow Me:
Github: github.com/gitdagray
Twitter: / yesdavidgray
LinkedIn: / davidagray
Blog: yesdavidgray.com
Reddit: / daveoneleven
Was this tutorial about creating custom React hooks with Axios helpful? If so, please share. Let me know your thoughts in the comments.
#axios #react #hooks

Опубликовано:

 

7 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 144   
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You will truly discover the power of React custom hooks when you understand custom hooks are not limited to returning data values - they can also return functions with all the power of the hook! This tutorial gives two examples: 1) a useAxios hook that returns values and 2) a useAxiosFunction hook that returns a callable function. They both have good use cases - let me know which you like better! Or are there any changes you would make? Just getting started with React? I suggest going to my React JS for Beginners full course here: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-RVFAyFWO4go.html
@heathery2997
@heathery2997 2 месяца назад
Dave, I can`t express my gratitude enough. I was learning react based on your videos 90% and i got my first frontend job! Not only that, tho, any time I need to do smth there, that I don`t know how to do, I usually can find it in your videos. Thank u so much. Im grateful for all eternity
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 месяца назад
Congratulations! This is the feedback I enjoy the most! 🎉🎉
@user-tj9po6bd6z
@user-tj9po6bd6z 3 месяца назад
You are a true mentor. Thank you for your easy to follow, clean and concise web dev content. You are quite literally “The Man”.
@hussaingagan9196
@hussaingagan9196 Год назад
It's better to reset the error state in the useAxios hook. If an error occurs and is set, subsequent requests made through that hook will still display the error if we don't reset it. Therefore, it is better to reset the error state after receiving our response. This ensures that any previous errors are cleared, and we start with a clean state for each new request. Like this:- setResponse(res.data); setError("");
@isurujn
@isurujn Год назад
I'm not a web dev. I came across this video while looking for React Native content. Just want to say your style of teaching is great! Very clear and concise. I wish you had React Native tutorials too 🙂
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thank you, Isuru! I hope to do a React Native series in the future. 💯🚀
@amosalfred
@amosalfred Год назад
Thank you very much Dave. Your tutorials are excellent and are far better than many paid tutorials. Well done. You are well appreciated. I like the second hook.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You are very welcome!
@karldtrumpeter
@karldtrumpeter Год назад
This was so helpful to me, Dave. I can't thank you enough, I'm grateful!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're very welcome!
@fares.abuali
@fares.abuali 2 года назад
Thank you so much, Mr. Dave. I have been learning a lot from you recently
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome!
@wishexploder
@wishexploder 2 года назад
Great video, very clean and clear, and I love the speed. Cheers :)
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you very much! 🙏🚀
@AbiodunSam
@AbiodunSam Год назад
Well done Dave Gray. Both methods are really useful. I still prefer the simplicity of the first hook with out function. Thank you.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're welcome!
@youssefkarfouh3084
@youssefkarfouh3084 3 месяца назад
thank you dave , front-end dev from morocco , i really love your tuts ❤❤👌
@DaveGrayTeachesCode
@DaveGrayTeachesCode 3 месяца назад
Glad you like them!
@anjaneyulub2529
@anjaneyulub2529 10 месяцев назад
Thank you dave learning new from u every day😊
@aramzand
@aramzand 2 года назад
Just on time. Thanks :)
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome!
@janekalam
@janekalam Год назад
Top-notch as always!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thank you!
@willyhorizont8672
@willyhorizont8672 2 года назад
Nice tutorial as always, thanks again.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome, Willy! 💯
@yaakovisaacs
@yaakovisaacs 2 года назад
Ok, this is insanely cool and you have mad skills. Where is your intermediate / advanced React course? I want, want, want now, now, now
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you for the kind words 💯 No intermediate course yet, but I've added tutorials for all the hooks on my channel. 🚀
@iamprincemuel
@iamprincemuel 2 года назад
awesome content as always. 💯💯💯
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you! 🙏
@hungnguyencanh5089
@hungnguyencanh5089 Год назад
Thank you, Dave!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Welcome!
@mikeseman6598
@mikeseman6598 Год назад
Thanks for the video. You're a great teacher. I liked the little things - let vs. const. and I never new I could turn off that warning on dependencies. I checked out your blog, yes I like Neil DeGrass too, the universe is like coding.. endless.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're very welcome! And thank you for the kind words! 🙏🚀
@taalaibeko
@taalaibeko Год назад
Best explanation, thanks a lot!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You are welcome!
@NamNguyen-oz8uj
@NamNguyen-oz8uj 2 года назад
Thank you very much Dave
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome!
@piyushmahapatra5402
@piyushmahapatra5402 2 года назад
Dave , thank you !
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome! 🚀
@quofintech9200
@quofintech9200 2 года назад
Your videos are awesome!, thanks
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you! 🙏🙏
@gabrielgropescu2453
@gabrielgropescu2453 2 года назад
Hi Dave, firstly thank you so much for your lectures, They are very neat, clear and inspiring as I watch over and over again. I have a minor observation though regarding *axiosFetch* function in *useAxiosFunction* hook. If we look at 24:00 minute in the video, the code is as: const res = await axiosInstance[method.toLowerCase()](url, { ...requestConfig, signal: ctrl.signal, }); Instead, I _would_ suggest: const res = await axiosInstance({ url, method: method.toLowerCase(), ...requestConfig, signal: ctrl.signal, }); setResponse(res.data); return res.data; This will satisfy the generic axios#request(config) function signature, and we should be able to send the *requestConfig.data* payload in the correct desired format, especially in POST method. Additionally, by returning *res.data*, we would be able to access the response data on the caller function, like in a login page to navigate further in the application. Thank you once again for your time.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
These custom hooks can definitely be modified to suit your needs. If that change works for you, I say go with it! 💯 My provided format usually works for me, but that's the great thing about code - there's never usually only one way to solve the problem.
@takeshiom8950
@takeshiom8950 Год назад
I am trying as well modify the code, your solution is good. In this code we can send FormData but cannot send simple data without formData. Did you to that with this? i tried to send post data "aplication/json" format using this code/ I have error because no any data in payload. How to make it ?
@davidhusted817
@davidhusted817 Год назад
I think you must add accept proberties in the req.config because we are inherit that object in the app
@ronpb3943
@ronpb3943 Год назад
Thanks, I was trying to get something like you did in your second approach but I was doing a few things wrong
@harag9
@harag9 Год назад
Great tutorial, though I did run into some issues because I switched to use VITE and TS... More fool me, but I did get it working so Yea, Go Me! ;) Many thanks for the lessons. Much appreciated.
@nathanielugbomah7447
@nathanielugbomah7447 Год назад
Hi Dave, thanks for the lovely videos you put out. I hope our appreciation will serve as motivation for you to continue. I prefer the useAxios function. However, I am still struggling to use it for delete and update when using a control form (that is, passing user id from a form)
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thank you! To help with your delete and update requests using an id - it can be passed in 2 different ways depending on how the server expects to receive it. 1) If the server expects the id to be a URL parameter, you need to pass the id in as part of the URL according to how the server wants to receive it. 2) This scenario is more likely for a delete or update request - the id is sent in the body of the request and should be included in the body of the Axios request.
@leooramone
@leooramone Год назад
i found gold, thanks!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Welcome!
@saulbenavides4037
@saulbenavides4037 6 месяцев назад
Great!
@alvinacosta2312
@alvinacosta2312 2 года назад
hi dave, thanks for your awesome content. I have a question though regarding the refetch function to force a re-render, can I place fetchData outside useEffect and it receives controller, and just invoke fetchData inside the useEffect that receives controller as an argument? then instead include fetchData in the return values of useAxios and use fetchData for the onClick listeneter of the button that fetches another joke?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
I'm missing something in the explanation of your question, but overall, you can tweak these custom hooks to meet your needs. If you want to return a different function, give it a try! 💯🚀
@sonamohialdin3376
@sonamohialdin3376 2 года назад
Excellent tutorial
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you, Sona! 🙏
@sonamohialdin3376
@sonamohialdin3376 2 года назад
You are welcome
@DH-jw4th
@DH-jw4th 2 года назад
Hello Dave. Early in the series you mentioned that you may cover npm styled-components to help customize the look of react apps. Still in the plans? Thanks for this great series!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Yes, I would like to. So many things to cover and that's good! I'll make sure this is still on my list. 💯
8 месяцев назад
brilliant.
@laminemessaci3302
@laminemessaci3302 Год назад
Thank you very much Dave, I have been learning a lot from you recently
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Very welcome!
@thetech3624
@thetech3624 Год назад
Thank you for this tutorial. Do you also have a tutorial on the basics to advanced of axios?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
I do not, but that could be a good idea for a future tutorial.
@137dylan
@137dylan 2 года назад
Hi Dave...thanks for sharing this. Quick question please: Around 19 mins or so, why create another handler function ("refetch") to reset the joke, when you could just pass in and then invoke the useState setter function ("setReload") directly?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You mean the hook could return the setter function and then invoke it in the receiving component if I understand correctly? The only benefit of creating the refetch function there is to abstract the task of updating the state - especially since the state update is just triggering the refetch and not providing any specific data to the task. The refetch function doesn't need anything passed in and simplifies this call.
@danieljing9319
@danieljing9319 2 года назад
nice content , Awesome
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you! 🚀
@neenus
@neenus Год назад
Dave thanks for simplifying it and especially thank you for showing how to abort a call while creating an axios hook ... I have one off topic question... when you were setting state you used vs code multi cursor edit however how did you type but the two words type one in all small caps and the other with first letter capitalized ex: when you typed error in your usestate [error, setError]??
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Look for the extension "multiple cursor case preserve" 🚀
@jmdavaul
@jmdavaul 2 года назад
What key combinations did you use to update the [reload, setReload] to [controller, setController] .. that was very cool
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
With the word reload in there twice, I highlighted the first word and then pressed Ctrl+D to select the 2nd instance. At that point, you can change both with what is called a multiple cursor. This used to be an issue though because the 2nd word was capitalized. There is a VS Code extension that handles this now though - "Multiple Cursor Case Preserve" extension. Good stuff!
@Corzhy0
@Corzhy0 2 года назад
Could you please do a video on the best way to handle errors with api requests?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thanks for the request! 🙏
@manyaj3750
@manyaj3750 2 года назад
Thanks for this post. I'm following your channel. All of the contents are very well explained. I have a question related to this demo. Please let me know if you have an answer for it. In Jokes component is it possible to consume the "useAxios" hook on click of "Get Joke" button instead of component load (assume refetch is not implemented)? Seems like this hook can be used only in a react function component root level or inside a custom React Hook function.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
With hooks, you can only use at the top level. I'll refer you to the official docs and rules of hooks: reactjs.org/docs/hooks-rules.html
@PedroTorres-og1te
@PedroTorres-og1te Год назад
Hey Dave! Thank you so much for this video. I know you made a video with the changes to be made because of React 18. Now with the release of the new version of Axios the changes to be made are a little bigger, would it be possible to make a video with an updated version of this hook?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Sounds like I need to do that. Tech keeps moving!
@stepanrudiak95
@stepanrudiak95 Год назад
@@DaveGrayTeachesCode i found 2 ways to fix it. 1. setError('') in try block const fetchData = async () => { try { const res = await axiosInstance[method.toLowerCase()](url, { ...requestConfig, signal: controller.signal, }); setResponse(res.data) setError('') } 2. add another useEffect but it triggers 1 more render // useEffect(() => { // setError(''); // }, [response]) What is the best way to fix it in your opinion ?
@templendukwu1664
@templendukwu1664 2 года назад
Hello Dave thanks for your class. i have a question, i am lil confused about the destructing inside the jokes.js component while writting the return values in the useAxios custom hook you did return [response, error, loading ] but while destructuring in jokes.js file you wrote const [ joke, error, loading ] what happened you did not use response instead of joke? or does it mean we can use any name for response state .. Thanks you are good
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
When the hook returns an array [value, value, value], we can name those anything we want at import - so I just renamed the data to joke when I imported. You can do this when destructuring objects, also - but you have to be a bit more specific const { data: joke, error loading } for example. Of course, you only do this if the hook returns an object and not an array.
@templendukwu1664
@templendukwu1664 2 года назад
@@DaveGrayTeachesCode Thanks so much Dave! you are truly doing a great job.... You inspire me a lot. i have been struggling to make logic statements its my concern now. can you put up a discord or a platform where we can interact
@marcellvajda9746
@marcellvajda9746 Год назад
Hey Dave! I have a question, was there a specific reason for using an array instead of an object as the hooks return value? Thanks for the help!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Not really - you can use whichever you prefer.
@abhaypatil5880
@abhaypatil5880 Год назад
I have a question here we are storing all res array in setRes state , if we submit another post what we want is to add that post in the res array, so that when user clicks submit button the post displayed will be 101 , 102 and so on, and how Can I achieve that in Posts component
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
When the component loads, a custom hook like useAxios will fetch the posts. Depending on how your app is structured, you could handle this in different ways. One way is to update your local state when you submit the new post by adding the new post to the local state as well as sending it to the REST API server. Another way is to have the new post form in a separate component, and then when you reload your posts list component, useAxios should be called again. A third way is what React Query, RTK Query and others do - they label cached data and when that cached data is invalidated, they request new data again. This third option goes a bit beyond the useAxios hook shown here, but it is the next step.
@kurshad020
@kurshad020 Год назад
Hi, thank you for the great educational videos. I have a question tho, how can we use this custom hook with the onChange property in the input section when we want to set a data ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
I'm not sure I understand your question as it relates to Axios. Axios is used to send requests to a server. Setting data with a change handler changes the current state. If you need to send state data with Axios you can, but you do not set the state when using Axios.
@kurshad020
@kurshad020 Год назад
@@DaveGrayTeachesCode Hi thanks for the quick reply. I ment the event listeners to post when you use the axios and want to capture data in the input then you need to put onchanche/ref event listeners. How can we use that for the custom axios ?
@mohamedyoussef8835
@mohamedyoussef8835 2 года назад
Awesome as always ++++++++++++++++++++++++++++++++++++
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you!
@shawslayer1
@shawslayer1 Год назад
Hi Dave. I have an issue when using useAxiosFunction. When I try to do a delete request, I get the status code 204 which then removes my list from the page. On refresh I see the delete was successful as it returns the rest of the list minus the deleted one. My guess is that the response state is set to an empty string from the 204 status code. Not sure how to fix this.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You may be experiencing an issue due to React 18's strict mode. I cover this in detail and refactor this useAxios custom hook for React 18 here: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-81faZzp18NM.html The refactor may be in this video instead: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-N41B_SVdzwg.html
@mindlord22
@mindlord22 Год назад
Hi Dave , thank you for making this really awesome tutorial. I am extremely stuck when I tried to implement this with typescript and react , because I am always getting the red squiggly line under the data part of `userId: ${posts.data?.userId} , the error is telling me that Property 'data' does not exist on type 'any[]' . The problem is when react is rendering at that moment the posts.data is undefined and it is showing me this errror while rendering also. Is there any work around this with useEffect or any other way ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
While this question goes beyond this tutorial, you can solve it in several ways. Many Stackoverflow posts for: fetch + typescript + undefined - like this post: stackoverflow.com/questions/69007670/typescript-fetch-data-from-server-and-loading-state ...I think looking at why you have the any inferred value would be the first step. What can you defined for TS to understand - that should help!
@mindlord22
@mindlord22 Год назад
@@DaveGrayTeachesCode Thank you so Much Dave for the extremely fast answer. I really appreciate all your tutorials and it is really taking my react skills to another level , I do hope that you can in the future have some kind of detailed react typescript course on udemy also. Please continue with this work have a great day.
@wagnerfillio1031
@wagnerfillio1031 2 года назад
Hi, good video. thanks. But can you give a tip on how to upload a file?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
This will get you started: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-9Xh_ZpFkROI.html
@msurabhi23
@msurabhi23 Год назад
This is a nice tutorial to learn on top of redux. Had a quick question. I used create-react-app and did a follow along. The dad joke load did not work for me. It keeps giving an error with the error message as cancelled. From the code the only difference i could see is the way react 18 createRoot is used. Can you please let us know how to fix this. - Replace ReactDOM.render with ReactDOM.createRoot instead to reproduce the issue
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
It is due to the behavior of strict mode in React 18. I cover it here: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-81faZzp18NM.html
@VimeshShah93
@VimeshShah93 2 года назад
Super tutorial. Thank you Please give me vs code theme name which you are using.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
GitHub theme
@mohsensami3141
@mohsensami3141 Год назад
in useAxiosFunction i want to add body and header in request give me example please
@GabrielMartinez-ez9ue
@GabrielMartinez-ez9ue 2 года назад
You should have a discord channel where we can interact with you!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Great request! I am getting ready to do that 💯🚀
@frostyfreezemovies
@frostyfreezemovies 2 года назад
Yeah...!! U right
@conevskidaniel911
@conevskidaniel911 Год назад
With the useAxios hook when using the cleanup function the hook returns both the response data and also catches an error with canceled message. So, when i use const [joke, error, loading, refetch] = useAxios.... there is both joke data and error with "canceled" message. Does anybody else have the same problem?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
This is likely due to React 18 strict mode. It mounts twice in strict mode and calls the cleanup function once. The cleanup function will create the canceled error message. I cover this new React 18 strict mode here: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-81faZzp18NM.html
@conevskidaniel911
@conevskidaniel911 Год назад
@@DaveGrayTeachesCode I will look into it. Massive thank you for your content and your way of teaching it !
@JoaoVitor-fy4jq
@JoaoVitor-fy4jq Год назад
I liked useAxiosFunction but I had problems with the controller when adding an infinite scroll in my project
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
I updated this hook for React 18 when introducing React 18 in this video: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-N41B_SVdzwg.html - It could be that strict mode might be causing the problem you are experiencing.
@elinordeniz
@elinordeniz Год назад
Hello Dave, on my useAxios.js file useEffect return function runs first (so it cancel the connection for axios ) then fetchData() function runs. So I receive canceled error on the screen. I have had this kind of issue before on my other projects. Can you please help me?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
React 18 strict mode: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-81faZzp18NM.html
@elinordeniz
@elinordeniz Год назад
@@DaveGrayTeachesCode You have no idea how you are contributing to my life on my way to become a developer. You are such a person that I dont know anyone like you in the world. Thank you very much for your all effort and help.
@imxande6930
@imxande6930 2 года назад
Hi Dave thank you again for the video. I have a question what does this piece of code do? axiosInstance[method]. I understand what it means but I dont know what kind of sorcery is this haha sorry not good enought with javascript. So thanks to you I understand that axiosInstance is passed in and it is the result from axios.create(whateverObjectHere), and I also understand that the method will hold the http method we want to use. But the array surrounding the method is the part I don't understand. It feels that I am missing so sort of basic javascipt shinanigans that I have never seem before. Could you please refer me to what is this technique/rule please? Are we accessing the method property in the axiosInstance object? Is that what it is?
@imxande6930
@imxande6930 2 года назад
Oh maybe we are just adding the method to the axiosInstance using bracket notation? lol I think I got it now lol. So complex ok here we go: so the method is actually coming from the configObject that we are receiving, thus when we destructure we get the post or get or whatever method we pass in the object and we store it in the method variable. Then we add this method variable that holds our http method to out axiosInstance using the bracket notation. am I to far from the truth? lol the grind is real Dave haha, again this is so much fun thank you.
@satellitesage2487
@satellitesage2487 2 года назад
@@imxande6930 I've been trying to figure this out as well. Here's what I think. From the documentation, we can do the following: axiosInstance.get(url[, config]), axiosInstance.delete(url[, config]), and so on. But in this video, we're trying to dynamically invoke an object method using a string variable (method var in our case). And the syntax for that is yourObject[stringVarContainingMethodName](). Hence, we have axiosInstance[method]().
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You've got it right here! 💯
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
I think you are saying the same thing that IMxAnDe described in his reply which is spot on.
@trezormubabe313
@trezormubabe313 2 года назад
Good job Dave. so i get this issue {message: 'canceled', name: 'CanceledError', code: 'ERR_CANCELED'} how can i fix it please
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Hello Trezor, this means you are using the new React 18 Strict Mode in your app. I discuss this in detail with this Axios hooks tutorial as an example here: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-N41B_SVdzwg.html
@sinaukode
@sinaukode 2 года назад
This is basically implement react-query library right???
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
I could compare them someday. It is currently about writing your own custom hook with Axios.
@1219Kal
@1219Kal 4 месяца назад
i have a question, i did exactly what you do. but my code has a error message 'calceled, signal is aborted without reason.' could you tell me how to fix it? thank you
@1219Kal
@1219Kal 4 месяца назад
does this error cause by StrictMode?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 4 месяца назад
Yes. This tutorial was made with React 17. React 18 introduced the double mount with useEffect and strict mode. Video covering the solution here: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-81faZzp18NM.html
@1219Kal
@1219Kal 4 месяца назад
@@DaveGrayTeachesCode Thank you for the explaination~~~
@regilearn2138
@regilearn2138 2 года назад
Hi Dave,please do a video how to use react router v6 on your MERN app,
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
This should help with RRv6: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-XBRLVRjZ3CQ.html
@regilearn2138
@regilearn2138 2 года назад
@@DaveGrayTeachesCode Appreciate your support. Thank you.
@cra2yjoker
@cra2yjoker 2 года назад
Hmm.. not sure why I'm getting request canceled when using useAxios but working fine with useAxiosFunction..
@LettuceLeav3s
@LettuceLeav3s 2 года назад
I am also getting this. Does anyone have an answer?
@devripxy
@devripxy 2 года назад
i too 🤔
@Pareshbpatel
@Pareshbpatel Год назад
An excellent tutorial on creating two reusable React Hooks. Thanks, Dave. {2022-10-27},{2023-09-12}
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Glad it was helpful!
@ConorChinitz
@ConorChinitz 2 года назад
Thanks for the video, Dave. One thing I was wondering--at 19:35, why did you decide to make the onClick function an anonymous function that calls refetch instead making refetch itself the onClick function? That is, why did you do this: onClick={() => refetch()} Instead of this: onClick={refetch} I'm wondering if there's something I'm missing.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
I'm in a habit of doing that because I often pass in the event with onClick functions, but you're right - this should work without the anonymous function here. Good refactor catch!
@ConorChinitz
@ConorChinitz 2 года назад
Ok, cool. Thanks for the quick reply. For what it's worth, I believe React will automatically pass the event as an argument to the onClick function (similar to how Express automatically passes req and res into each piece of middleware). So it should still work to write onClick={refetch} even if you want to do something with the event. You can give refetch an 'event' parameter in its function definition to get access to it. function refetch(e) { console.log(e.target); }
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
This is accurate, but I was referring to often writing onClick anonymous functions that need the event which are usually setting state like: (e) => setState(e.target.value) ..in which case I need to pass the event. Yes, I could write a handleClick function that then uses setState, but I think we both understand what we are talking about :) Thanks again for the note!
@alext5497
@alext5497 2 года назад
There is so much bad info out there. There is great though
@selestial7
@selestial7 22 дня назад
terrible video.didnt explain anything and brushed past the main points without explain squat.
@eazydatasolutions5800
@eazydatasolutions5800 Год назад
useAxiosFunction hook 💯 by 1000, Dave you are the Best . Thank you so much and God Bless You!!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're welcome! I update this hook for React 18 in part of this video: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-N41B_SVdzwg.html
Далее
The Most Impressive Basketball Moments!
00:36
Просмотров 13 млн
Why Signals Are Better Than React Hooks
16:30
Просмотров 460 тыс.
Context API in react | get the concept
29:00
Просмотров 44 тыс.
How to Fetch Data in React With A Custom useFetch Hook
16:37
TypeScript Generics are EASY once you know this
22:21
Просмотров 126 тыс.
Learn React Hooks: useCallback - Simply Explained!
17:15