React Axios API Requests | Axios with React JS Tutorial

แชร์
ฝัง
  • เผยแพร่เมื่อ 21 ก.ค. 2024
  • Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
    Learn React Axios API Requests in this tutorial. We will implement Axios with React JS as we build our React JS Blog project. Axios makes API requests easier than using the Fetch API in Javascript.
    💖 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
    🚀 This lesson is part of a Learn React tutorial series playlist:
    • React Tutorials
    🔗 Project Source Code: github.com/gitdagray/react_ax...
    React Axios API Requests | Axios with React JS Tutorial
    (00:00) Intro
    (00:05) Welcome and Tutorial Outline
    (00:26) JSON Server set up
    (02:06) Installing Axios
    (03:29) Setting a baseURL for Axios
    (04:44) Starting JSON Server
    (05:21) Starting the React app
    (06:27) Import the Axios API
    (07:08) Fetching data with Axios
    (13:35) Posting data with Axios
    (17:05) Deleting data with Axios
    (18:23) Building the handleEdit update function
    (23:08) Creating the EditPost component
    (30:24) Adding a Route for the EditPost component
    (31:52) One more addition to the EditPost component
    (32:56) Adding an Edit Post button to the PostPage component
    (33:59) Importing EditPost and testing functionality
    (35:54) Small CSS Changes
    🔗 Axios:
    www.npmjs.com/package/axios
    🔗 React Router:
    reactrouter.com
    🔗 JSON-Server:
    www.npmjs.com/package/json-se...
    🔗 ES7 React JS Snippets Extension for VS Code:
    marketplace.visualstudio.com/...
    🔗 React Dev Tools Extension for Chrome:
    chrome.google.com/webstore/de...
    🔗 Styled Components: styled-components.com/
    📚 References:
    MDN Flexbox: developer.mozilla.org/en-US/d...
    ReactJS Official site: reactjs.org/
    React Wikipedia: en.wikipedia.org/wiki/React_(...)
    React Jobs: www.ziprecruiter.com/candidat...
    ✅ Follow Me:
    Twitter: / yesdavidgray
    LinkedIn: / davidagray
    Blog: yesdavidgray.com
    Reddit: / daveoneleven
    Was this tutorial about Axios API Requests in React helpful? If so, please share. Let me know your thoughts in the comments.
    #react #axios #api
  • วิทยาศาสตร์และเทคโนโลยี

ความคิดเห็น • 102

  • @DaveGrayTeachesCode
    @DaveGrayTeachesCode  3 ปีที่แล้ว +17

    Axios is a lightweight npm package that makes requesting data easier than Javascript's built-in Fetch API. In this tutorial, you will learn how to add Axios to your project and use it for all CRUD (create, read, update, and delete) operations in the project. If you are just starting out with React, I suggest starting at the beginning of this Learn React series playlist here: th-cam.com/play/PL0Zuz27SZ-6PrE9srvEn8nbhOOyxnWXfp.html

    • @MyALPHAguy
      @MyALPHAguy ปีที่แล้ว

      It really discourages me learning when I bump into an old version of React Router... I was watching and practicing all of your lessons until I've come across an old version of React Router...

  • @mrFighter924
    @mrFighter924 3 ปีที่แล้ว +2

    The best React ( the whole series ) explanation on entire internet. I love you approach, thank you man

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +1

      You're welcome! And thank you for the kind words 🙏

  • @minsupark9246
    @minsupark9246 3 ปีที่แล้ว +5

    OMGGGGGGG!!!! I was looking for React Axios video and your video came up to my recommendation!!! XD!!! Besides, I'm 1st visitor to this video!! haha Thank you Dave~ !

  • @lavitzwind6709
    @lavitzwind6709 3 ปีที่แล้ว +2

    I've been waiting for this one. Thank you Dave for these react series are awesome.

  • @akshitkushwaha9479
    @akshitkushwaha9479 4 หลายเดือนก่อน

    TYSM Mr.Gray super helpful !!!

  • @thedevguild7525
    @thedevguild7525 2 ปีที่แล้ว

    Impressive, can tell you are a very experienced developer when you code on the go, while speaking.

  • @DH-jw4th
    @DH-jw4th 2 ปีที่แล้ว +4

    Dave, as an avid youtube tutorial consumer, I must say your teaching is outstanding. After watching the Node/Express/MongoDB series which contains an extensive section on authentication and JWT authorization I was looking forward to your React client side implementation… Did I miss it? If not, your contribution in that area would, I am sure, be appreciated by many.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว

      Great suggestion! I need to create a tutorial to tie that together 💯

    • @baxtables
      @baxtables ปีที่แล้ว

      @@DaveGrayTeachesCode is there a tutorial connecting react and node with authentication Dave?
      If yes, please provide the link. Thanks

  • @xen0n20p7
    @xen0n20p7 7 หลายเดือนก่อน

    What will be the route for editpost element in version 6. Can you please help me with it. Thanks,.

  • @danieltkach2330
    @danieltkach2330 2 ปีที่แล้ว

    Hi Dave, I'm researching this, and I have a question since I see you don't address it in the video. I see you are hardcoding "localhost" on the axios.create() function. How do you handle the way the app works in production vs locally? What's the method you use to check if you are running on a deployed version? I've been using the interceptors, but I'm just guessing you can give a much more precise answer and correct way on how to do this. Much appreciated.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +2

      Good questions, Daniel! After development, I often switch out "localhost" along with any port number so "localhost:3000" for example - and change it to the actual web address of the REST API I will be using. The routes you use in development - that is the part of the address that comes after the base URL like /posts or /todos or /whatever - those routes should be the same in development that you will use with the actual REST API. To answer your other question, you can check to see if React is in "development" or "production" mode with this value: process.env.NODE_ENV ..use a console.log() statement to check the value in your index.js.

  • @ivanfrey6323
    @ivanfrey6323 2 ปีที่แล้ว

    Clarifying question, for the first parameter inside of the AXIOS call which is the path `/posts/{id}`, id is a numerical value, does the URL path only work with numerical values? For example, if I tried to find a post using the title property instead of the id which stores a string value, and the path was `/posts/{title}` that doesn't seem to work, why is that?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว

      That is all dependent on what your backend server expects to receive. If my memory is correct, this tutorial uses a mock API ran with JSON Server. It expects to receive the post id when requesting a specific post - which is not unusual. Here is another practice API that you can read about and see how it expects to receive requests: jsonplaceholder.typicode.com/

  • @skillkrio
    @skillkrio ปีที่แล้ว

    Dave in the timeframe 26:32 the dependency list of the useeffect post,setEditTitle and setEditBody seems redundant to me because individual post is not gonna change so it will not trigger the useeffect. Every functionality works fine with empty dependency list. Whats the reason of adding the setEditTitle and setEditBody and post over there?If empty list works fine

    • @chrisstucker1813
      @chrisstucker1813 ปีที่แล้ว

      if you use any functions or variables in a useeffect, you need to include them in the dependency array . That's just the rules otherwise you will get warnings

  • @rogelgabrielcristobal7730
    @rogelgabrielcristobal7730 2 ปีที่แล้ว

    hey dave, I am having a hard time understanding the built in fetch API of javascript , this tutorial helps me a lot.. thanks

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +2

      You're welcome! This video uses Axios which is not quite the same as the built-in Javascript Fetch API. I do have a tutorial about using Fetch here: th-cam.com/video/VmQ6dHvnKIM/w-d-xo.html

  • @premmourya7060
    @premmourya7060 3 หลายเดือนก่อน

    awesome ♥

  • @michaelalbrecht4346
    @michaelalbrecht4346 2 ปีที่แล้ว

    Somewhat unrelated question, but I'm going through a university Web Security course right now. Our textbook states that bad hackers can gain clues on how to hack the system from error messages that are too detailed. The error messages provide them with clues. Should we log error messages to console if that is the case? Maybe this applies more to server side than client side error messages...? Just curious on what you think about the way to structure error messages and on logging them to console.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว

      Good question, Michael. It's all preference really. The console.error and other console statements are typically removed in production deployments. On the backend, errors should be logged. On the frontend, you can choose what to display if you want to display them in production.

  • @BrainNotUsed
    @BrainNotUsed 2 ปีที่แล้ว +2

    Thank you for great tutorial serie.
    I am afraid that I have some questions:
    Is there any reason that you prefer PUT vs PATCH request for axios?
    I tested and there is not visible difference, are there any performance or other aspect to be aware of?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +6

      Good question! You won't see a difference with PUT vs PATCH. PATCH is supposed to be for partial modifications while PUT is for replacing the entire record. That is why I used PUT. All data was being replaced. More request type definitions on MDN here: developer.mozilla.org/en-US/docs/Web/HTTP/Methods

  • @isaacnewtonaranas3770
    @isaacnewtonaranas3770 2 ปีที่แล้ว

    that subscribe sound 3:53 sounded to me as some has coughed in the room while im alone. anyway this tutorial is very very AWESOME for someone like a beginner like me. Thanks so much!!!! very very helpful!

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +1

      😂 Didn't intend to scare you. I'll have to listen to it again.

    • @isaacnewtonaranas3770
      @isaacnewtonaranas3770 2 ปีที่แล้ว

      @@DaveGrayTeachesCode haha you dont have to reupload the video! it's unique! thanks for replying, felt special :)

  • @user121304
    @user121304 2 ปีที่แล้ว

    Hi Dave. Thank u for this awesome tutorial. I have a doubt , Can we use axois to fetch data from firebase? I believe we don't need the json server in that case. Please let me know. Thanks.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +1

      Yes, JSON server is just for your dev environment. You can use Firebase for the backend of your app in production or a Node JS backend like I show how to build in my Node JS for Beginners course.

    • @user121304
      @user121304 2 ปีที่แล้ว

      @@DaveGrayTeachesCode Thanks Dave. I will try to connect to the firebase DB and update u if I have any issues. Appreciate all ur great efforts. U r the best instructor I have seen so far on TH-cam. May God bless u !!!!

  • @tienhuynh2435
    @tienhuynh2435 9 หลายเดือนก่อน

    just amazing

  • @kari.s5488
    @kari.s5488 2 ปีที่แล้ว

    Bro, thank YOU !!!

  • @GilbertoTrin
    @GilbertoTrin ปีที่แล้ว

    Hi Dave. Thank u for this awesome tutorial. I have a doubt, why the useEffect function at EditPost.js is not been called everytime the state of input field changes?
    If you put that function (setEditTitle) in the dependencies why this not triggering the useEffect?
    Thanks

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      You're welcome! 💯 React understands that the setState function is not changing. useEffect will only run if the dependencies listed in the dependency array change.

    • @GilbertoTrin
      @GilbertoTrin ปีที่แล้ว

      @@DaveGrayTeachesCode Ok, right, but when would setState function change? I understood the changes in post object, but not in functions.
      Thanks

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      @@GilbertoTrin setState won't change, but older versions of React used to give warnings if you didn't include it in the useEffect dependencies. It is not necessary and I think the warnings for setState have been stopped, too.

    • @GilbertoTrin
      @GilbertoTrin ปีที่แล้ว

      @@DaveGrayTeachesCode Thanks. Great Job

  • @wilsonibekason
    @wilsonibekason 2 ปีที่แล้ว

    you are a blessing

  • @ashharkausar413
    @ashharkausar413 2 ปีที่แล้ว

    Excellent video

  • @caffeinated-pixels
    @caffeinated-pixels 3 ปีที่แล้ว

    Thanks Dave, you've convinced me to give Axios a try in my current project!

  • @shravanp8091
    @shravanp8091 2 ปีที่แล้ว

    when hosting on github pages, what updates do make for the API file URL and fetching in the async? also, great tutorial!

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว

      Thank you. The JSON server API we set up is just for our development environment. You cannot host an API on Github Pages. If you complete my Node.js full course for beginners, you will learn to build your own REST API. You can then host it Heroku or Glitch or Repl (and more) for free.

    • @shravanp8091
      @shravanp8091 2 ปีที่แล้ว

      ​@@DaveGrayTeachesCode is there any other way to host this project without going through that? like with Netlify?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว

      @@shravanp8091 Netlify will host React and other frontend projects, but it does not host backend projects that run on a server - Node.js, PHP, Python, and other backend technologies.

  • @siddiqahmed3274
    @siddiqahmed3274 2 ปีที่แล้ว

    Sir I have a small question... Why did you put setEditTitle, setBodyTitle as dependency for useEffect at 26:58. I don't think it is needed there as that function only has to run at load time

    • @siddiqahmed3274
      @siddiqahmed3274 2 ปีที่แล้ว

      Besides they both are sort of functions to set the values of editTitle and editBody, isn't it? Then their value would never change so why to put them as dependency?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +3

      Good question! You are right that they will not change and should not be needed. However an eslinter doesn't recognize this and adding them doesn't harm anything. I think I did it to avoid the warning from an eslinter like this one: "React Hook useEffect has a missing dependency: 'setSomeState'.
      Either include it or remove the dependency array.
      eslint(react-hooks/exhaustive-deps)"

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +1

      More discussion on this here: stackoverflow.com/questions/59709304/setstate-in-reacts-useeffect-dependecy-array

    • @siddiqahmed3274
      @siddiqahmed3274 2 ปีที่แล้ว

      @@DaveGrayTeachesCode Okay sir Thank you

  • @masudalimran92
    @masudalimran92 ปีที่แล้ว

    hello sir. why does it say bash in your terminal. Did you change any settings from default. My terminal shows cmd

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      I installed the bash terminal when I installed git. If you have more than one, you can choose from a drop menu.

  • @agroforestryconsultancyroz3157
    @agroforestryconsultancyroz3157 2 ปีที่แล้ว

    Thanks sir!

  • @damarmurti
    @damarmurti ปีที่แล้ว

    On 29:08, Dave put handleEdit on the button instead of onSubmit event inside the form element. I tried to put it on the onSubmit event and it worked, the post did change but then after I passed on e.preventDefault(), it stopped working. The console printed something about "uncaught in promise". Anyone care to explain?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      At 29:08 - as you noted - I show how to do this. You could create a handleSubmit function above the returned JSX which has both the e.preventDefault() in it as well as the call to handleEdit with the post.id passed in. In this beginners tutorial - I show in the example at 29:08 - how to do this with functions created directly inside the JSX.

    • @damarmurti
      @damarmurti ปีที่แล้ว

      @@DaveGrayTeachesCode Alright thank you very much for the explanation

  • @PolarisMyWay
    @PolarisMyWay 7 วันที่ผ่านมา

    but what about timeouts?

  • @dimitriss3635
    @dimitriss3635 2 ปีที่แล้ว

    I am building a blog in react aswell and what i ve done,is i ve set up an express server connected to my database to handle data,is it wrong,or is it just an other way?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +1

      It is not wrong. It is a great way to do it! This course / playlist just focuses on React so we set up a fake REST API with JSON server instead of building a backend.

    • @dimitriss3635
      @dimitriss3635 2 ปีที่แล้ว

      @@DaveGrayTeachesCode ok, thanks for the feedback Dave, keep up the awesome work

  • @johnmarynwanze3713
    @johnmarynwanze3713 ปีที่แล้ว

    Please I need help, I'm fetching the data from the API but it not displaying any data(info) I don't know if it's API or my error and I'm just learning how to call API using axios, including the requestconfig and so many more

  • @elmvple
    @elmvple ปีที่แล้ว

    Hey Dave, I have a bug in my app so I'm thinking it could possibly be in yours as well? I'm not exactly sure what the issue is but when I click on a post, edit post, and delete all of the title (completely blank), it automatically takes me to "Page not found." Please let me know if you experience this issue as well and what's the fix. Thanks!
    Also, really enjoying your series!

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      Thanks - no problem in my example code - BUT things to consider: 1) If you are on the blog project, look for the updated React Router link in the description because React Router was updated after this course was released. 2) React is now on React 18 instead of React 17, but this should not have an impact in the code for this course. Nevertheless, it is worth noting.

    • @rishikchakravarty7986
      @rishikchakravarty7986 11 หลายเดือนก่อน

      I am facing the exact same bug, how do I resolve it?

  • @unpluggedaman
    @unpluggedaman 2 ปีที่แล้ว

    Thanks a lot

  • @melfordbirakor
    @melfordbirakor 2 ปีที่แล้ว

    Thank you

  • @inv1ctu_545
    @inv1ctu_545 ปีที่แล้ว

    Sir after I wrote the code for the update posts everything was working fine. But the app won't allow me to create changes in the posts. It says ' failed to load resource'. Is there anything I could have possibly missed?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      Yes, you could have missed something. Use diffchecker.com to compare your source code to the source code available in the course resources.

    • @inv1ctu_545
      @inv1ctu_545 ปีที่แล้ว

      @@DaveGrayTeachesCode sir i checked and i have done everything correctly. Only the Routing part is different in React 18. I think it's an error in my computer or system itself. However, I understood the axios api concept very well. So thank you for the video and the reply!

  • @hardwired89
    @hardwired89 3 ปีที่แล้ว

    thank you sir

  • @aes0p895
    @aes0p895 ปีที่แล้ว +5

    i'm just going to give my friendly feedback: i know time is valuable, and people are learning at all different levels, but even as far as just learning axios, this seems like less of a tutorial and more "dave (briefly) shows people how he does things". while i of course don't expect you to be explaining how destructuring works and things like that, i don't really see the point in a tutorial that goes from point to point without even explaining what each step is generally accomplishing. I'm good with going back to docs to understand things, but if I can't really understand why I'm doing a thing, there's very little point. just a little more time spent on that would be a massive difference. Anyway I appreciate the effort and you seem like a great teacher, this is just feedback on this particular video.

    • @rishikchakravarty7986
      @rishikchakravarty7986 11 หลายเดือนก่อน +1

      This is what I exactly feel after seeing Dave Gray's tutorials, they are not for absolute begineers, I had to study react from the documentation and then see this playlist, even for it to just make sense

    • @TheLastPhoen1x
      @TheLastPhoen1x 19 วันที่ผ่านมา

      He explains it in /watch?v=XYrNkTkx8Uc, this video is "How to accomplish with AXIOS the same things we did with fetch in default react".
      If you come upon this video by just searching something like "how to use AXIOS" and haven't watched the previous one then it may look a bit rushed, but explaining everything again would be redundant for people who are following the series step by step.

    • @aes0p895
      @aes0p895 18 วันที่ผ่านมา

      @@TheLastPhoen1x Yeah, that's fair, but the nature of TH-cam kind of dictates the format. When I buy a full course, then of course I don't want redundancy, but YT videos should be self-contained in my opinion. Which is why I prefer Web Dev Simplified or Net Ninja to 90% of what's on TH-cam, simply because everything is included.

  • @spacecorp1669
    @spacecorp1669 ปีที่แล้ว

    Is there any way to get to talk to you ? I love the fact that you are one of the few that speaks very clearly. But I have a concept to convey.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      You can join my Discord where we discuss all things.

    • @harag9
      @harag9 ปีที่แล้ว

      I agree, he's a very good speaker and very clear. If you do C# coding or want to learn I would recommend Tim Corey. He's very good too.

  • @harag9
    @harag9 ปีที่แล้ว

    Great tutorial, many thanks for this. However you seem to be missing the useEffect return and aborting the API calls - I know you want to keep this simple but you didn't mention aborting and possible issues.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      Thank you and you are right that I wanted to keep this simple here in a beginners course. The examples you are looking for are here: th-cam.com/video/NqdqnfzOQFE/w-d-xo.html

    • @harag9
      @harag9 ปีที่แล้ว

      @@DaveGrayTeachesCode Excellent, thanks for the link Dave, I'll check that out, I noticed in the next video however "custom hooks" you go over the clean up a little. Loving the series!

  • @dikshitsai1080
    @dikshitsai1080 2 ปีที่แล้ว

    I followed this video When i'm updating and deleting the user(instead of post ) i'm seeing this error "Failed to load resource: the server responded with a status of 404 (Not Found)" Even i checked in the backend controllers i have used this code in update
    export const updateUser = async (req, res) => {
    const { id } = req.params;
    const { email, first, last, avatar } = req.body;

    if (!mongoose.Types.ObjectId.isValid(id)) return res.status(404).send(`No post with id: ${id}`);
    const updatedUser = { email, first, last, avatar: id };
    await User.findByIdAndUpdate(id, updatedUser, { new: true });
    res.json(updatedUser);
    }

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว

      If the server sends a 404, it is not finding the route and does not reach the code in your controller. It must be something with the route provided.

    • @ulutsoft-tutorials6130
      @ulutsoft-tutorials6130 2 ปีที่แล้ว

      I just wrote axios.put instead of api.put and get route error, maybe you did something like this. Just check your code again

  • @Metovski
    @Metovski ปีที่แล้ว

    Is this react blog project was a mern project ?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      No, I have a separate course for a MERN Stack Project. The projects in this series are just about learning React.

  • @omrishooshan9784
    @omrishooshan9784 2 ปีที่แล้ว +1

    im no begginer but its an helpfull tutorial for all levels

  • @abdulrahmanagboolaosho3582
    @abdulrahmanagboolaosho3582 ปีที่แล้ว +1

    so no more fetch yaay

  • @nikolasfuruta6938
    @nikolasfuruta6938 ปีที่แล้ว

    just in case someone having trouble with rendering edit-component after refactoring to react-router-6. Look at PostPage and change the edit Link to ......and be happy.

    • @kunr4104
      @kunr4104 ปีที่แล้ว

      Thanks for the reminder, I implement this with and put the edit route underneath the post route as