Full React Tutorial #17 - Fetching Data with useEffect

Поделиться
HTML-код
  • Опубликовано: 7 янв 2021
  • Hey gang, in this React tutorioal we'll see how to make a fetch request for data using the useEffect hook.
    🐱‍💻 🐱‍💻 Course Files:
    + github.com/iamshaunjp/Complet...
    🐱‍👤🐱‍👤 JOIN THE GANG -
    / @netninja
    🐱‍💻 🐱‍💻 My Udemy Courses:
    + Modern JavaScript - www.thenetninja.co.uk/udemy/m...
    + Vue JS & Firebase - www.thenetninja.co.uk/udemy/v...
    + D3.js & Firebase - www.thenetninja.co.uk/udemy/d...
    🐱‍💻 🐱‍💻 Helpful Links:
    + HTML & CSS Course - • HTML & CSS Crash Cours...
    + Modern JavaScript course - • Modern JavaScript Tuto...
    + Get VS Code - code.visualstudio.com/
    🐱‍💻 🐱‍💻 Social Links:
    Facebook - / thenetninjauk
    Twitter - / thenetninjauk
    Instagram - / thenetninja

Комментарии • 227

  • @user-ct5oo3do7b
    @user-ct5oo3do7b 3 года назад +5

    Async version:
    useEffect(() => {
    async function fetchBlogs() {
    let response = await fetch('localhost:8000/blogs');
    response = await response.json();
    setBlogs(response);
    }
    fetchBlogs();
    }, []);

  • @Jmendiola
    @Jmendiola 2 года назад +7

    Bro you're a life saver, I am a bootcamp student who almost quit because I can't keep up with react, now here, I am getting hope to continue, I press like and watch all the ad to show my support to your channel, please stay awesome sir, God bless!

  • @amanpreetsinghbawa1600
    @amanpreetsinghbawa1600 3 года назад +19

    The best part of tutorials is you have them backed by the course files.
    Very well managed.

  • @aliaksandrhn1
    @aliaksandrhn1 Год назад +72

    5:40 You could have easily corrected the error by using an empty array rather than null as an initial state: const [blogs, setBlogs] = useState( [] );

    • @KingstonFortune
      @KingstonFortune Год назад +5

      thanks for this tip! glad I took a glance at the comments and found yours as number 1

    • @pratyushpurohit
      @pratyushpurohit Год назад +26

      He could but his point was to teach us a new concept. Glad he didn't use []

    • @ziaurrahman9529
      @ziaurrahman9529 Год назад

      thanks!

    • @seclvded
      @seclvded Год назад +4

      damn, u da mvp. but i also like how he explained it (in case u run to his exact problem)

    • @kavinsanthosh1306
      @kavinsanthosh1306 Год назад

      yeah bro. but why it is not preventing the rendering of blog list. when theoritcally it should?

  • @CarlosSGonzalezV
    @CarlosSGonzalezV 3 года назад +3

    Man thanks so much! You won't believe how many days I've been searching how to do this, finally I got to your playlist and I'm gonna watch it from the beginning to properly learn React again.

  • @googleaccount7252
    @googleaccount7252 Год назад +5

    Tip for those struggling, make sure that you have two terminals running, one for react the other for db. and make sure you .db file is saved.

  • @melancholicmuse
    @melancholicmuse 2 года назад +3

    This course is my first introduction to React and i'm enjoying the lessons so much

  • @86Illa
    @86Illa 3 года назад +46

    Thank you so much for this course! Your way of explaining is extremely clear - I have used React for a while now, but at times things still get confusing. You make everything extremely clear :)

  • @DigitalMonsters
    @DigitalMonsters 3 года назад +45

    Set blogs initial state to an empty array if you don't want to have to conditionally render with the double ampersand. Since an empty array is still a valid map object.

    • @karanparmar4318
      @karanparmar4318 3 года назад +6

      True,
      But I think he did this purposefully to make us understand about conditional rendering.

    • @reactdev7871
      @reactdev7871 3 года назад +1

      I was just gonna say that good job buddy as I made a real blog with an API here and made a search box on the navbar that can search and filter the blogs so was confused with this null issue so I find out that using empty array fix the issue :D

    • @defaultdefault812
      @defaultdefault812 2 года назад +1

      Need to be careful that no .length method is evaluated.

    • @sabinoramirez2600
      @sabinoramirez2600 2 года назад +2

      problem with this approach is the title will display even if the array is empty. This looks ugly in real world application

    • @ericmomoh7927
      @ericmomoh7927 2 года назад +1

      @@reactdev7871 please can I see the code on how you made the search bar?

  • @conanfahytelleria6251
    @conanfahytelleria6251 3 года назад +21

    I love all your tutorials, you explain it all so clear!

    • @NetNinja
      @NetNinja  3 года назад +4

      Thank you so much! :)

    • @tomaszswiatek4612
      @tomaszswiatek4612 3 года назад +1

      yep i agree:), and I'm still up to date with this awesome n1 tutorial :)

  • @samtakahashi5602
    @samtakahashi5602 2 года назад

    THIS.
    Was working on an Update/Edit function to finish off this series and was stuck for a few hours wondering why my data properties were returning null...
    Thank you for this fantastic course!

  • @olorundareagnes934
    @olorundareagnes934 2 года назад

    I must say that you are a superb teacher.
    Well done Shaun!

  • @yangliu3754
    @yangliu3754 3 года назад +5

    Great solution to deal with the null!
    After the data is fetched and the setBlogs is invoked, React re-renders the whole component, and this is why when the blogs value changes the (blogs && ) part runs again.

  • @henrydinh285
    @henrydinh285 2 года назад

    OMG! Glad i saw this video. The logical && solved my problem i had for days as im learning react and hooks. Thanks Shaun ❤

  • @ayushdudhani
    @ayushdudhani Год назад

    Thanks alot !
    I was using axios while getting data!!
    It was for my hackathon,
    used same way as you shown!!
    it worked!!
    THANKS ALOT MAN !!!!!!

  • @towseefahmed6328
    @towseefahmed6328 3 года назад +5

    ur simply excellent ... explanation is outstanding... thanks a lot for this excellent content

  • @CodeRCreatives
    @CodeRCreatives 3 года назад +3

    You are really very awesome teacher very nicely explained all the concepts of reacts.

  • @andrewpenny1285
    @andrewpenny1285 Год назад

    You solved a problem for me that has been very discouraging. I forgot to set initial stage to null and also forgot about the conditional rendering. I was getting the error about mapping over an undefined array. Thank you again and again!

  • @jennifermagpantay7933
    @jennifermagpantay7933 2 года назад

    Great tutorial!! After a few minutes watching it I found
    out a solution for a bug! Brilliant!

  • @eylemgokdemir
    @eylemgokdemir 2 года назад

    BEST json server tutorial. THANK YOU!

  • @samirprasla1770
    @samirprasla1770 3 года назад +4

    Thank You so much for your such hard work on all of your tutorial videos, you are very polite and honest teacher !! too the point tutorials all of them are very well explained....!!

    • @NetNinja
      @NetNinja  3 года назад

      Thank you so much! 😃

  • @maskman4821
    @maskman4821 3 года назад +5

    Thank yoy Shaun for this tutorial, I have learned a valuabke lesson which is conditional template, now I finally understand why and how { blogs && } works, it feels so good to comprehend the reason behind this !!!

  • @ScottRocke
    @ScottRocke 2 года назад +1

    Thank you for the clear and concise video. Definitely helped unblock some brain cells.

  • @monson2048
    @monson2048 Год назад

    Amazing content! Love your explanations!

  • @bobhammell6308
    @bobhammell6308 Год назад

    Very consise tutorials, great for picking up the concepts. Thank you!

  • @madannikalje760
    @madannikalje760 2 года назад +2

    Thank you so much this helped me alot ngl I was stuck in that error for long time I wasn't able display my fetch data

  • @akashnegi913
    @akashnegi913 3 года назад +2

    Your Videos are right on Time
    So are we , Thank You :)

  • @gorkemgok9313
    @gorkemgok9313 6 месяцев назад

    Man you deserve a prize or something as the best youtube code teacher.

  • @youngun550
    @youngun550 Год назад +4

    I would absolutely love it if you did a brief tutorial on how to externalise an async await code block. I've managed something close, but I still want to abstract away.. Thanks for the awesome content! Really enjoy your videos, by far the most helpful I've come across :P

    • @parthdesai9751
      @parthdesai9751 11 месяцев назад

      at this point, you could probably ask chatgpt

  • @billpapas3054
    @billpapas3054 3 года назад

    What a god explanation and teach!!!!! Adtonishing buddy!! Ty

  • @AbrahamWilson
    @AbrahamWilson 3 года назад

    Dude your tutorials are excellent, seriously enjoying the content. Could you please make a course where you show how to make CRUD apps using the MERN stack.

  • @Eldalion99999
    @Eldalion99999 3 года назад +2

    single most useful react video in whole youtube......do you have any idea how long it took me to find all these different pieces of information condensed in this video ??? Especially the 2x .then part....jezus the things I tryed to achieve that. I wish I had this 6 months ago.....

  • @elora2334
    @elora2334 2 года назад

    Thank you, its so clear with your explain !

  • @azeezalsafadi901
    @azeezalsafadi901 Год назад

    I learned a million things from this lesson
    Thank you The Net Ninja!!

    • @NetNinja
      @NetNinja  Год назад

      You're very welcome Azeez! :)

  • @AlDasturchi
    @AlDasturchi 20 дней назад +1

    The most useful account ever

  • @Pupu._
    @Pupu._ 3 года назад +1

    clear explanation as always! :)

  • @oleksiik4473
    @oleksiik4473 3 года назад

    Hi, great job, thank you for your work! In this course, in a feature we see Redux?

  • @jonaskarl
    @jonaskarl 3 года назад

    Very good Playlist! Thanks.
    Is there a way, I can read and manipulate the blogs state in multiple components?

  • @vidmis224
    @vidmis224 2 года назад +1

    You are life saver mate!!

  • @princearthur5532
    @princearthur5532 Год назад +1

    Wow you are great at explanations i have tried several tutorials but this tops it.

    • @NetNinja
      @NetNinja  Год назад

      Great to hear :) thanks Prince!

  • @dineshrout2527
    @dineshrout2527 3 года назад

    Love the way you teach 🙏

  • @DimpleNov
    @DimpleNov 10 месяцев назад

    Hey! I found this video very late after i stepped into development . I wish i found about this channel earlier. Thank you so much for providing this great information. Also, we set the initial state for the blog data as 'null' . Could we use an empty array for that as well ? That way , i didn't get the error 'cannot read map of null'

  • @sirusThu
    @sirusThu 2 года назад

    Amazing explanation. thanks

  • @LoveisHell85
    @LoveisHell85 3 года назад

    Amazing content. Thank you so much.

  • @Ishant56
    @Ishant56 2 года назад

    Wow amazing Tutorial Thank You ❤️

  • @RodRavenpictures
    @RodRavenpictures Месяц назад

    The goat. (period)

  • @staplepin8099
    @staplepin8099 3 года назад +4

    Best teacher

  • @khedubaba
    @khedubaba 3 года назад

    Pure and sweeet knowledge.

  • @martiananomaly
    @martiananomaly Год назад

    The use of && was pretty smart.

  • @Rose-93
    @Rose-93 Год назад

    Thank you fo such a clear explanation :)

  • @Doimaixinhtuoi
    @Doimaixinhtuoi 3 года назад +1

    In stead of initializing the blogs state with null value, is it ok to use an empty array?

  • @filmbotreviews
    @filmbotreviews Год назад

    Thanks so much for this video, helped me with the problem I was having.

  • @mdkarim831
    @mdkarim831 3 года назад

    Thanks a bunch for these tutorials! Do you think you could show how to properly implement google OAuth 2.0 in a reactjs app? I have done an implementation but it looks very incorrect especially my redirect part.

  • @mohammadawais163
    @mohammadawais163 2 года назад

    Excellent Explanation❤

  • @KerishaStewart
    @KerishaStewart 8 месяцев назад

    Your videos are amazing!

    • @NetNinja
      @NetNinja  8 месяцев назад +1

      Thank you so much! :)

  • @Se.mu01
    @Se.mu01 3 года назад

    Just what I needed

  • @olgapolskolg1112
    @olgapolskolg1112 2 года назад

    Thanks a lot, you helped me to solve a problem

  • @SofianMW
    @SofianMW 3 года назад

    Perfect my friend!

  • @teetphum
    @teetphum 2 года назад

    Thank you so much!! you save my web app

  • @rogeclash2631
    @rogeclash2631 Год назад

    many thanks for this , it is very clear

    • @NetNinja
      @NetNinja  Год назад

      Thanks Roge. Glad to hear that!

  • @anony4142
    @anony4142 4 месяца назад

    Thanks for the explanation, but I have a simple question why we did not use asynchrounous function so we won't render anything till the blogs are returned from the fetch ?

  • @GiancarloCarccamo
    @GiancarloCarccamo 2 года назад

    great video man

  • @CrookzArtwork
    @CrookzArtwork 3 года назад

    So clean

  • @drifung
    @drifung 2 года назад

    thanks for the tutoriel

  • @maxbisceglie1682
    @maxbisceglie1682 3 года назад

    Shouldn't the component update after blogs is updated without the conditional rendering? I thought the state variables were reactive... I'm a bit confused sorry

  • @abdulazizalzamil6872
    @abdulazizalzamil6872 3 месяца назад

    Thanks for the series.
    Question here: Why the blogs didn't get set to the value being returned from the fetch? Shouldn't the return statement wait until the fetch function finishes since it uses promises and everything should wait till it finish its work? And like that the value of blogs wouldn't be null. I want explanation to what happened :)

  • @alexanderhungerford8246
    @alexanderhungerford8246 2 года назад

    great summary at 6:39

  • @nerdiloo9863
    @nerdiloo9863 3 года назад

    "Maann, you are Metacmucil" 🔥🔥🔥

  • @bananabread6758
    @bananabread6758 Год назад

    excellent video

  • @bartekk6480
    @bartekk6480 2 года назад

    thanks so much!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • @AngryBacteria
    @AngryBacteria Год назад

    I now know how to only display something when the useFetch has the data from the json server. But how would I go about only doing a certain action if the json object is loaded? For example I only want to fill an array once the data is loaded but I dont know how to do it

  • @PapsOSk19
    @PapsOSk19 2 года назад +1

    Great tutorial, thanks. I have just one question, how do you fetch it and map it inside the same component?

    • @akeymthedream
      @akeymthedream Год назад

      I think you can do so by using props to access blogs and then mapping the props in the BlogList component

  • @x9wozz
    @x9wozz 3 года назад

    Can't wait for more :D
    Also will you explain why we ended up using hooks instead of class components? I suppose it's because of things like mentioned before useEffect hook and more. Though I'm neither familliar with react class components so I don't know if I'm not wrong here

    • @maskman4821
      @maskman4821 3 года назад +1

      If you are new to react, just learn hooks, always go with the latest technologies !

    • @x9wozz
      @x9wozz 3 года назад +1

      @@maskman4821 but the thing is that most companies still use things that were written before hooks update and that's often the case that you have to deal with legacy-ish code. That's why learning class components is relevant for me, since I'm aiming to transfer from just being frontend dev to react dev*.
      *from what I've noticed there's a lot more of corpo work as frontend dev than actual programming as react dev if that makes sense.

  • @RameenFallschirmjager
    @RameenFallschirmjager 3 года назад

    I know this comment is the most irrelevant comment ever, but I couldn't help myself! I was watching your Vue udemy course and I reached the section that you were teaching how to emit events. I am familiar with this concept, because I learnt it when I was studying game development with godot engine. I got so excited for this "flash of enlightenment!" that I needed to show my gratitude somehow! This incident proves that it's important to expand your knowledge and how knowing some stuff in other areas helps to solidify your skills and knowledge as a whole. And I suggest everybody does it, I mean to try various stuff, it's good for your health!

  • @huntershub3030
    @huntershub3030 Год назад

    !!!!!!!!!!!!!!!!!!!THANK YOU!!!!!!!!!!!!!!!!!

  • @amjadaliafridi1023
    @amjadaliafridi1023 Год назад

    it has been a superb journey so for

    • @NetNinja
      @NetNinja  Год назад

      Awesome to hear that Amjad!

  • @skipper3204
    @skipper3204 Год назад

    I'm wondering why would you use null as initial state of blogs. For me it works when initial state is empty array so it doesn't throw an error at the start. Any help?

  • @shawnshaw9859
    @shawnshaw9859 10 месяцев назад

    first time when blogs was checked and it's null, what will happen, will it be rechecked regularly until it becomes non-null?

  • @johnsmith-oy9kx
    @johnsmith-oy9kx 3 года назад +1

    Excuse me if I'm asking too much, please do a 'react native 2021' tutorial in 'net ninja' style, it will help us a lot. I know there are a lot of react native courses out there but we like it in net ninja style - simple, sharp and comprehensive. PLEASE...

  • @sheeshaliosama5837
    @sheeshaliosama5837 11 месяцев назад +1

    I did the same thing you did but it keeps giving me errors ('blogs.map is not a function') and (Failed to execute 'json' on 'Response': Illegal invocation) can you explain the problem and how to solve it please

  • @fatihkaya6817
    @fatihkaya6817 3 года назад +2

    could you show how do we implement fetching data in backend and passing the data via Express routes to frontend? This would be very helpful simple full stack implementation

  • @LorandPalfalvi
    @LorandPalfalvi 2 года назад

    Thank you!
    I would have loved it if you would have used async/await instead of then.
    Almost nobody uses .then anymore.

  • @michaelsd28
    @michaelsd28 3 года назад

    thank you a lot

  • @ajaykumarpulletikurthi2558
    @ajaykumarpulletikurthi2558 2 года назад

    You are the God

  • @a.i.v7306
    @a.i.v7306 2 года назад

    How are you using react with regular .js files? I get errors on all my return code for my compnents when I try doing that. I have to have them be .jsx. Well Im using typescript so tsx

  • @ankush3707
    @ankush3707 3 года назад

    can we have multiple use effect in a component?

  • @ziekaman2450
    @ziekaman2450 2 года назад

    setBlogs method? Where did you initiate that method?

  • @krishnakanth4576
    @krishnakanth4576 2 года назад

    thanks a lot!

  • @themoroccanpianist8953
    @themoroccanpianist8953 2 года назад

    does this tutorial talk about the latest version of ReactJS (17) ?

  • @ForwardTokage
    @ForwardTokage 2 года назад

    life saver 😭

  • @Bashir3675
    @Bashir3675 Год назад

    As you said it takes some time for the data to be fetched, that is why it is not available initially. But how using && is making the data available ? or is it taking some time until the the data gets fetched? Can somebody explain?

  • @NuclearAmouri
    @NuclearAmouri 2 года назад +1

    5:15 Couldn't we just initialize `blogs` to an empty array?
    const [blogs, setBlogs] = useState([]);

  • @nicholaspucharelli711
    @nicholaspucharelli711 2 года назад

    helpful video

  • @RahulSharma-ph2zn
    @RahulSharma-ph2zn 2 года назад

    after fetching api with useEffect when i reload the page on the browser. there is an error like,
    the initial state of the post is [ ] (a blank array).
    useEffect is call after the render. so the setPost can change the state later.
    and map function on a blank array is not possible.

  • @jumbo999614
    @jumbo999614 3 года назад

    How come useQuery and usePaginatedQuery not included in this series?
    I know there is another tutorial series about useQuery. But the package is updated and the code taught in that series no longer work with new version.

  • @satishganesan54
    @satishganesan54 Год назад

    Hi!!!... I am facing problem while fetching data , getting errors like err connection refused and am finding it hard to get solution in web and also I have faced issue in watching the json data after global installaton like running scripts is not allowed in this system..could you please reply?

  • @Dgrayfit
    @Dgrayfit 2 года назад

    In regards to the 6:00 minute mark. So the idea with the {blogs && ... } code here is that because we have initially set the state of blogs to be null we will initially get blogs to evaluate as false, so the logical && won't fire since both conditions must be true. However, we 'react' to the new render by updating the state of blogs in the useEffect() hook, which then makes blogs evaluate to true and our component evaluate to true. I think I am following, but if anybody can spot a gap in my understanding please jump in.

    • @andrewpenny1285
      @andrewpenny1285 Год назад

      You are correct, but the conditional rendering wouldn’t be so important if it wasn’t for the map method being called on the data in the other component. Mapping over undefined data will throw an error and the app will fail to load anything at all. Basically, we are waiting until the data has arrived before we start trying to pass it around or render it.

  • @hlpires101
    @hlpires101 Год назад

    thx !!

  • @nuke7
    @nuke7 3 года назад

    I see the promise on line 15 here, but the next .then does NOT work.
    I see the values inside the promise object - HOW DO I GET THEM OUT of there?!
    (no matter what dependency array I use...)

  • @rahulsriram6295
    @rahulsriram6295 3 года назад +1

    If you take the initial value as Empty array instead of null, it works too