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: ruclips.net/video/RVFAyFWO4go/видео.html
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
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("");
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 🙂
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.
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: ruclips.net/video/N41B_SVdzwg/видео.html
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?
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: ruclips.net/video/81faZzp18NM/видео.html
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.
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.
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.
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.
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 ?
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 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 ?
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
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)
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.
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?
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.
@@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]().
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?
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! 💯🚀
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!
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
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.
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]??
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!
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
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.
@@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
I updated this hook for React 18 when introducing React 18 in this video: ruclips.net/video/N41B_SVdzwg/видео.html - It could be that strict mode might be causing the problem you are experiencing.
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
Yes. This tutorial was made with React 17. React 18 introduced the double mount with useEffect and strict mode. Video covering the solution here: ruclips.net/video/81faZzp18NM/видео.html
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 ?
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.
@@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 ?
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.
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?
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.
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 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.
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.
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: ruclips.net/video/81faZzp18NM/видео.html The refactor may be in this video instead: ruclips.net/video/N41B_SVdzwg/видео.html
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 ?
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!
@@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.
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.
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!
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); }
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!
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: ruclips.net/video/RVFAyFWO4go/видео.html
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
Congratulations! This is the feedback I enjoy the most! 🎉🎉
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("");
You are a true mentor. Thank you for your easy to follow, clean and concise web dev content. You are quite literally “The Man”.
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 🙂
Thank you, Isuru! I hope to do a React Native series in the future. 💯🚀
thank you dave , front-end dev from morocco , i really love your tuts ❤❤👌
Glad you like them!
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.
You are very welcome!
Well done Dave Gray.
Both methods are really useful. I still prefer the simplicity of the first hook with out function.
Thank you.
You're welcome!
Ok, this is insanely cool and you have mad skills. Where is your intermediate / advanced React course? I want, want, want now, now, now
Thank you for the kind words 💯 No intermediate course yet, but I've added tutorials for all the hooks on my channel. 🚀
Thank you so much, Mr. Dave.
I have been learning a lot from you recently
You're welcome!
This was so helpful to me, Dave. I can't thank you enough, I'm grateful!
You're very welcome!
Thank you dave learning new from u every day😊
Thanks, I was trying to get something like you did in your second approach but I was doing a few things wrong
Best explanation, thanks a lot!
You are welcome!
Great video, very clean and clear, and I love the speed. Cheers :)
Thank you very much! 🙏🚀
Thank you, Dave!
Welcome!
Good job Dave. so i get this issue {message: 'canceled', name: 'CanceledError', code: 'ERR_CANCELED'} how can i fix it please
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: ruclips.net/video/N41B_SVdzwg/видео.html
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?
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: ruclips.net/video/81faZzp18NM/видео.html
@@DaveGrayTeachesCode I will look into it. Massive thank you for your content and your way of teaching it !
Thank you very much Dave
You're welcome!
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.
Thank you very much Dave, I have been learning a lot from you recently
Very welcome!
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.
You're very welcome! And thank you for the kind words! 🙏🚀
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.
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.
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 ?
I think you must add accept proberties in the req.config because we are inherit that object in the app
Top-notch as always!
Thank you!
Nice tutorial as always, thanks again.
You're welcome, Willy! 💯
Dave , thank you !
You're welcome! 🚀
Thank you for this tutorial. Do you also have a tutorial on the basics to advanced of axios?
I do not, but that could be a good idea for a future tutorial.
You should have a discord channel where we can interact with you!
Great request! I am getting ready to do that 💯🚀
Yeah...!! U right
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?
Sounds like I need to do that. Tech keeps moving!
@@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 ?
Just on time. Thanks :)
You're welcome!
awesome content as always. 💯💯💯
Thank you! 🙏
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
It is due to the behavior of strict mode in React 18. I cover it here: ruclips.net/video/81faZzp18NM/видео.html
Your videos are awesome!, thanks
Thank you! 🙏🙏
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)
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.
i found gold, thanks!
Welcome!
Hi, good video. thanks. But can you give a tip on how to upload a file?
This will get you started: ruclips.net/video/9Xh_ZpFkROI/видео.html
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?
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.
@@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]().
You've got it right here! 💯
I think you are saying the same thing that IMxAnDe described in his reply which is spot on.
in useAxiosFunction i want to add body and header in request
give me example please
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?
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! 💯🚀
Excellent tutorial
Thank you, Sona! 🙏
You are welcome
Could you please do a video on the best way to handle errors with api requests?
Thanks for the request! 🙏
What key combinations did you use to update the [reload, setReload] to [controller, setController] .. that was very cool
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!
brilliant.
Super tutorial. Thank you
Please give me vs code theme name which you are using.
GitHub theme
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!
Not really - you can use whichever you prefer.
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
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.
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]??
Look for the extension "multiple cursor case preserve" 🚀
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!
Yes, I would like to. So many things to cover and that's good! I'll make sure this is still on my list. 💯
Great!
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
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.
@@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
Hmm.. not sure why I'm getting request canceled when using useAxios but working fine with useAxiosFunction..
I am also getting this. Does anyone have an answer?
i too 🤔
I liked useAxiosFunction but I had problems with the controller when adding an infinite scroll in my project
I updated this hook for React 18 when introducing React 18 in this video: ruclips.net/video/N41B_SVdzwg/видео.html - It could be that strict mode might be causing the problem you are experiencing.
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
does this error cause by StrictMode?
Yes. This tutorial was made with React 17. React 18 introduced the double mount with useEffect and strict mode. Video covering the solution here: ruclips.net/video/81faZzp18NM/видео.html
@@DaveGrayTeachesCode Thank you for the explaination~~~
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 ?
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.
@@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 ?
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.
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
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?
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.
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?
React 18 strict mode: ruclips.net/video/81faZzp18NM/видео.html
@@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.
nice content , Awesome
Thank you! 🚀
An excellent tutorial on creating two reusable React Hooks. Thanks, Dave.
{2022-10-27},{2023-09-12}
Glad it was helpful!
This is basically implement react-query library right???
I could compare them someday. It is currently about writing your own custom hook with Axios.
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.
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: ruclips.net/video/81faZzp18NM/видео.html
The refactor may be in this video instead: ruclips.net/video/N41B_SVdzwg/видео.html
Hi Dave,please do a video how to use react router v6 on your MERN app,
This should help with RRv6: ruclips.net/video/XBRLVRjZ3CQ/видео.html
@@DaveGrayTeachesCode Appreciate your support. Thank you.
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 ?
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!
@@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.
Awesome as always ++++++++++++++++++++++++++++++++++++
Thank you!
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.
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!
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);
}
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!
There is so much bad info out there. There is great though
useAxiosFunction hook 💯 by 1000, Dave you are the Best . Thank you so much and God Bless You!!!
You're welcome! I update this hook for React 18 in part of this video: ruclips.net/video/N41B_SVdzwg/видео.html
terrible video.didnt explain anything and brushed past the main points without explain squat.