Тёмный

React Redux Thunk Middleware in Redux Toolkit for Async Actions with Axios 

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

Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
In this React Redux Thunk Middleware tutorial, you will learn how to create async actions using Axios in Redux Toolkit. You will learn what a thunk is and how we create async thunks outside of a Redux slice.
💖 Support me on Patreon ➜ / davegray
⭐ Become a full-stack web dev with Zero To Mastery Courses:
- Advanced React & Redux: 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...
👀 React Redux Toolkit tutorial series - • React Redux Toolkit Tu...
📬 Course Updates ➜ courses.davegray.codes/
🔗 Source Code and Resources for this Redux Toolkit Series: github.com/gitdagray/react_re...
React Redux Thunk Middleware in Redux Toolkit for Async Actions with Axios
(00:00) Intro
(00:15) Welcome
(00:26) Prerequisite knowledge
(00:43) Faster Pace Ahead
(01:06) What is a thunk?
(01:34) Changing the initial state
(02:58) Adjusting to the state shape
(04:44) Creating a fetchPosts async thunk
(07:02) Adding extraReducers and builder cases
(10:08) Dispatching fetchPosts async thunk
(13:51) Building a PostsExcerpt component
(15:31) Displaying the loading state
(19:00) Creating a fetchUsers async thunk
(21:50) Dispatching fetchUsers at App load time
(23:25) Creating an addNewPost async thunk
(25:39) Dispatching the addNewPost async thunk
(29:15) Quick Correction
Corrections:
(06:22) Do not use try / catch blocks here as the video shows. You need the promise to be fulfilled or rejected which will have the appropriate response in the extraReducers.
☕ Buy Me A Coffee: www.buymeacoffee.com/davegray
📚 General Redux Toolkit References:
🔗 Official Site for Redux Toolkit: redux-toolkit.js.org/
🔗 Redux Devtools: github.com/reduxjs/redux-devt...
🔗 Immer.js: immerjs.github.io/immer/
🔗 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 Redux Thunk middleware for async actions with Axios in Redux Toolkit and React helpful? If so, please share. Let me know your thoughts in the comments.
#redux #thunk #middleware

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

 

20 июл 2024

Поделиться:

Ссылка:

Скачать:

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

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 266   
@morphine496
@morphine496 Год назад
I'm finishing my third app for my portofolio and this has helped me immensely. I love the way this guy explains it and the quality he brings.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Glad to hear that it helped!
@Phoenix-hp5rj
@Phoenix-hp5rj Год назад
what app did u make
@sirelee5169
@sirelee5169 Год назад
Highly agree.🎉
@rodinCodin
@rodinCodin Год назад
Thanks for your work, Mr. Gray! Im building out front end for one of my bootcamp projects and this is hugely helpful in navigating complex RTK environment!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Very welcome!
@cole_mcconnell
@cole_mcconnell 2 года назад
Super useful video, thanks so much this makes it so much clearer to me how to setup the architecture around thunks and async code involved with redux states!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Glad it helped!
@willyhorizont8672
@willyhorizont8672 2 года назад
Great tutorial Dave thanks, can't wait to see this async thunk with useAxiosPrivate hook you created in the series :)
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
They are similar. Our posts state has the posts, a loading state, and an error just like the custom Axios hooks structure. The extraReducers builder cases respond to the promise status returned where we set the state status. Very similar structures!
@willyhorizont8672
@willyhorizont8672 2 года назад
@@DaveGrayTeachesCode so you mean I can use axios interceptor inside extraReducers builder like that?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Not inside the builder case, but I did put axios inside the fetchPosts async thunk. It could be intercepted there before returning data.
@rammehar5531
@rammehar5531 2 года назад
Yeah, I always love to see your's full of knowledgable contents videos, Thanks Dave!! and please make a series of Typescript, NextJs with Redux Toolkit.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome and great requests! Those are on my list!
@harag9
@harag9 7 месяцев назад
Great tutorial, much appreciated, and well explained. Thanks.
@codegym2306
@codegym2306 Год назад
Thank you, Dave, your explanation gave me a more insight of async thunk
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Glad it was helpful!
@shineLouisShine
@shineLouisShine 5 месяцев назад
Thank you, Dave. It seems like one thing seperates this video and this entire Redux series from perfection: The absence of Redux Saga tutorial. If it is not too late to plug in another chapter - that will be more than welcome :) (...As well as your insights about the newRedux core 5.0, React-Redux 9.0, Reselect 5.0 {which I know totally nothing of}, and Redux Thunk 3.0....)
@prince5922
@prince5922 Год назад
This series is the most exhaustive Redux tutorial on youtube, thank you so much Dave. There are a few observations that I've had while following and I thought I might share them, at 28:15 inside the onSavePostClicked method the catch block in this case won't work because the unwrap method itself doesn't throw an error, we need to have an async function with await to achieve that functionality. Furthermore at, 5:59 and inside the fetchPosts thunk, inside the catch we are returning err.message; however, this won't work because we need to return a promise from the thunk callback and according to the promise result thunk will create and trigger the appropriate actions. Since this is not a promise thunk doesn't know what to do and it can't create and trigger the reject promise action. These are some of my observations. All in all, 'I'm really loving this series.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Good discussion! 1) The unwrap method can throw an error. See ( redux.js.org/tutorials/essentials/part-5-async-logic#checking-thunk-results-in-components ) for the same code and a further docs reference here: ( redux-toolkit.js.org/api/createAsyncThunk#unwrapping-result-actions ) ..."The promise returned by the dispatched thunk has an unwrap property which can be called to extract the payload of a fulfilled action _or to throw either the error_ ..." 2) Correct! 💯 This correction is already annotated for the video in the description and appears at 6:22. This is also already corrected in the provided Github source code. Glad you are enjoying the series!
@prince5922
@prince5922 Год назад
@@DaveGrayTeachesCode Thank you so much for responding, your reply made my day. Regarding the first point, the code in the docs, the reference of which you've shared, it has an "await" before the dispatch, but at 28:15 in the video, "await" isn't typed before dispatch, which I think is why I was having trouble catching the error.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
@@prince5922 ah I see! Good catch!
@learner8084
@learner8084 5 месяцев назад
Thanks very much for the video. I'm slowing watching and learning everything you show here. I benefitted greatly from your video. I understand much better now. I have a side question, I find the vertical line marking the block and also the horizontal line on the first line of the block very useful in following your video. May I know what extension or settings that enable this ? Thanks !!!
@dragosgheceanu9847
@dragosgheceanu9847 2 года назад
Was impressed by the HQ of the content. Very professional!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you! 🙏💯
@Kasiux
@Kasiux 2 года назад
This is insane! How can you make something that used to be just html files into this?! I mean... It's great, but....
@jagjens
@jagjens Год назад
Great video Dave, learnt alot from this one!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Glad it was helpful!
@mihirsharma3857
@mihirsharma3857 Год назад
Thanks Dave, For awesome playlist 🙏
@maxwellalexander6474
@maxwellalexander6474 Год назад
Great content. Its helping me a lot to learn redux. Thanks so much.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Glad to help!
@spondoolie6450
@spondoolie6450 Год назад
I was having problems where my API for posts was being called twice and giving me 200 posts (100 unique). I disabled strict mode and it solved the problem. I don't know if that was the main culprit or just a bandaid, but after watching this video 3 times to verify it's the only thing I could think of.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Yes, I made a video about this React 18 change: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-81faZzp18NM.html
@user-ug5ue9tq5j
@user-ug5ue9tq5j 2 года назад
I've never seen a tutorial like this. Thank you so much. Dave ☺️
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome! 🙏 Glad it was helpful!
@ahmedmusawir
@ahmedmusawir Год назад
Awesome stuff! As usual ... quick question, do you think we should include Axios since we have RTK query? Does the RTK query handle caching and everything on its own? I'd appreciate a reply since I'm learning the whole thing from you and there is no better tutorial available on the topic anywhere ... thanx in advance!
@Kourosh_ey
@Kourosh_ey 8 месяцев назад
That is my question too
@samiullahsheikh5015
@samiullahsheikh5015 2 года назад
13:40 As usual you are producing high quality content which is super awesome. Dave, I am little confuse about dependency array. Can you please explain the following point. I know the use of dependency array in useEffect but still didn't get it what is the purpose of puting dispatch in dependence array? Usually we put something in dependency array whose value change but dispatch itself is a function.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Good question, Sami. If using strict mode, you will get warnings about not including it in the console. It doesn't bother anything to be there, but I agree that it may not be necessary either. It was presented this way in the docs example I based the tutorial on, so I left it in there.
@codingispower1816
@codingispower1816 8 месяцев назад
In the postsSlice.js I notice that in the fetchPosts.fulfilled addCase, concatenating the loaded posts is making the posts come back twice. Fixed it by changing the line to state.posts = loadedPosts;@@DaveGrayTeachesCode
@wzup23
@wzup23 7 месяцев назад
Dude, thank you for this!
@garikmelqonyan9130
@garikmelqonyan9130 Год назад
Great tutorial, Dave. Thanks a lot
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're welcome!
@karlo768
@karlo768 2 года назад
Thank you so much, I've learned a lot from these videos
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Glad to hear it! 💯🚀
@ikurbano
@ikurbano 2 года назад
Hi Dave! Thanks for another great tutorial! I have a question. When you created a new post, you pushed it right away to the array of posts in the state. I think you dicided to go that way because the new post has not been pushed into the database which you get all posts from. Please, correct me if I am wrong. Also, if I am right, if you send (via post method) a new post into the same database which you get all your posts from, you need to dispatch fetchAllPosts again so that the new post show up along with old posts.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
In the extraReducers, the builder.addCase has an addNewPost case. If the promise is fulfilled, the state is updated there. That case responds to the addNewPost async thunk promise status.
@fithamlakfikrie4657
@fithamlakfikrie4657 Год назад
Thank you for this clear explanation!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You are welcome!
@yashpandey350
@yashpandey350 2 года назад
Thank you Sir for this great tutorial.😍😍😍😍
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome!
@user-ty5pd4xw2y
@user-ty5pd4xw2y Год назад
Thanks a lot for this fantastic explanation of Redux, Dave Gray. Would you please provide some guidance on the following bug: I keep getting every post rendered twice + 2 children with the same key red error.. unable to figure out how to fix this... many thanks))
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Yes, this is due to the new nature of React 18 strict mode. It only uses strict mode in dev mode. You can remove it OR you can replace the concat() call in this code and instead, create a new array with the spread operator.
@subhashgn1775
@subhashgn1775 2 года назад
Thank you for the great tutorial. How do we manage multiple Api calls in single component. Do we have to maintain separate loading, error and succeed variables for each of them or?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Good question. The API call is issued by the Async Thunk. If you were dispatching more than one thunk or dispatching the same thunk more than once, each thunk would handle its own API call. The extraReducers builder cases in the slice would respond to the thunks separately as well.
@dieuhuyen0812
@dieuhuyen0812 Год назад
Thankyou teacher. The tutorials are very good!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Glad you like them!
@lutfisken
@lutfisken 11 месяцев назад
Great video thanks. Still I think when looking in our own application with custom (simple in my opinion) implemenation of Redux (actions in one folder and reducers in one folder), where we are now thinking refactoring to Redux Toolkit, the whole createSlice() syntax seem to quickly get messy and hard read with one huge object as parameter where properties like "reducer" and "prepare", "extraReducers" etc in turn have there curly brackets and object.....Hope you see what I mean, kind of riskt to end up in spaghetti-syntax if not being careful . Still I will look in to it as I understand Redux Toolkit will be the standard way of setting up Redux.
@Lotpite
@Lotpite Год назад
really easy to undestand, thank for nice explanation
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You are welcome!
@omi7868
@omi7868 Год назад
thank you, Dave Gray. Much appreciated.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Very welcome!
@triTube70
@triTube70 2 года назад
Thanks Dave for the great videos, I learned a lot. One question, where do you use the first parameter you pass to the createAsyncThunk() function? The 'post/fetchPosts' string. How does ReduxToolkit use it?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Great question! The docs say "A string that will be used as the prefix for the generated action types". It is how Redux identifies the action, and you can see this in Redux Devtools. If we dispatch(fetchPosts()), you will see a 'posts/fetchPosts/pending' first and then either similar with fulfilled or rejected. I hope that helps!
@danieljing9319
@danieljing9319 2 года назад
First parameter is a string that will be used to generate additional Redux action type constants, representing the lifecycle of an async request: For example, a type argument of 'users/requestStatus' will generate these action types: pending: 'users/requestStatus/pending' fulfilled: 'users/requestStatus/fulfilled' rejected: 'users/requestStatus/rejected'
@ema_devolder
@ema_devolder 6 месяцев назад
A very above explanation...
@viditgoel2909
@viditgoel2909 8 месяцев назад
thanks for this amazing tutorial
@hosamgnaba3205
@hosamgnaba3205 Год назад
a very fat big like from me man, I really appreciate what you do here ? thank you
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're welcome, Hosam! 🙏
@MartinPerez-mi1ty
@MartinPerez-mi1ty Год назад
Thank you so much this was so helpful, greetings from Peru
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're very welcome! And hello to Peru! 👋
@mounis
@mounis 2 года назад
Great video Dave, thanks a lot. Is this the last video of Redux series?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you 🙏 and no, several more to come. Busy week this week. Next one, may arrive next week.
@techcheck3042
@techcheck3042 Год назад
Great tutorial! Thank you!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Welcome!
@salihhasan9662
@salihhasan9662 2 года назад
thank you Dave you are really help me so match
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome! 💯🚀
@mohamedyoussef8835
@mohamedyoussef8835 2 года назад
Best tutorial on RU-vid ... but you should not use try/catch in createAsyncThunk or .addCase(fetchPosts.rejected, will never be called. Just let it throw the error: const fetchPosts = createAsyncThunk('posts/fetchPosts', async () => { const {data} = await axios.get('/posts') return data })
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you for the kind words, Mohamed 🙏 and great catch! My try-catch habit got in the way here. You are correct, and I have updated the source code repos. 💯🚀
@nguyenanh-vt4jv
@nguyenanh-vt4jv 4 месяца назад
Thank you Dave, hope you have a video for redux saga
@DaveGrayTeachesCode
@DaveGrayTeachesCode 4 месяца назад
I don't but I have had a few requests.
@RahulSharma-wh8sq
@RahulSharma-wh8sq Год назад
Great content really impressive thanks a lot🙏
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're welcome!
@user-oe8hj9bc6c
@user-oe8hj9bc6c Год назад
This video is very helpfull for me, thanks a lot!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You are welcome!
@VietTranIT
@VietTranIT Год назад
Thanks, appreciate the excellent tutorial
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Glad it was helpful!
@jp-sc5du
@jp-sc5du Год назад
Hi Dave! I just came from your useAxios video. I'm curious if we can use the useAxios hook with createAsyncThunk and RTK in general? Let's say we put the dispatch call inside useAxios. I really like the reusability of custom hooks. I hope you can give answer as I have just started learning Redux and RTK and would love your guidance. Thank you!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
I know you can use Axios with async thunks and RTK in general. I haven't tried to use a custom useAxios hook with it. The docs have a recipe for an Axios baseQuery: redux-toolkit.js.org/rtk-query/usage/customizing-queries#axios-basequery
@muhammadnurali4347
@muhammadnurali4347 2 года назад
Hello, thank you for the great tutorial. After you called store.dispatch(fetchUsers()) in index.js, the AddPostForm component can access users state via useSelector, but when i checked the redux global state with redux devtools, there is only posts state. How came AddPostForm component access users state without it being saved in global state ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You may want to compare your code to my course resource code for lesson 3 as the users state is being saved. In the index.js, the fetchUsers function is imported from the usersSlice and dispatched with store.dispatch(fetchUsers())
@SanjarKodirov-ww3le
@SanjarKodirov-ww3le Год назад
awesome lessons, thank you
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Glad you liked it!
@mayanxoni
@mayanxoni Год назад
One thing worth mentioning at the end of the video is that when the new posts are added one after another, we get the following warning: Warning: Encountered two children with the same key, `101`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted - the behavior is unsupported and could change in a future version.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Note that this only occurs because the jsonplaceholder website doesn't really add the new posts. I have updated the course resources code to better handle this, but it would not be an issue if not for the jsonplaceholder site behavior.
@mayanxoni
@mayanxoni Год назад
@@DaveGrayTeachesCode thanks for the reply! I'll check it out.
@saquibasghar5152
@saquibasghar5152 Год назад
Hi Dave at 9:20, you added concat method to post array, when useEffect is called, reactStrict mode will make another GET request and the response will concat with the existing post array with new array, thus post length 200 and every post element is duplicatetd
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You are correct. This tutorial was made with React 17 before strict mode did that. Use the spread operator to create a new array instead.
@saquibasghar5152
@saquibasghar5152 Год назад
@@DaveGrayTeachesCode Thanks Dave for your reply, I used the spread operator. Again, thanks for generous contribution in making this kind of tutorial and helping future aspiring react developer in their career.
@hozayves
@hozayves 7 месяцев назад
@@saquibasghar5152 Hello friend, I have the same error for duplicated posts, Could you please help me to know how you resolve it.
@hozayves
@hozayves 7 месяцев назад
Problem resolved buddy Thanks a lot @DaveGrayTeachesCode , @saquibasghar5152 @saquibasghar5152
@vickysawant19
@vickysawant19 7 месяцев назад
@@hozayves // state.posts = state.posts.concat(loadedPosts) state.posts = [...loadedPosts];
@sahilatahar
@sahilatahar 7 месяцев назад
I regret why I didn't see your tutorial before I wasted my one 🕜 year 😢. Thank you Mr. Dave gray 😊
@jkkim6363
@jkkim6363 2 года назад
Hi Dave! First of all, really thanks for this amazing tutorial! :) And I followed this one, everything works well. But I have a question, When I add a bunch of new posts, that are more than two post, I found that they all have an id of '101'. so I saw the message "Encountered two children with the same key, `101` in the console. and I also found another related problem, when I clicked the reaction buttons, the buttons' response has a problem too. Could you check these problems? How can I solve this problem? How should I change the code?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Hello Kris - you can follow the link in the description to the resources for this Redux series and view my source code for lesson 3. Compare to yours for differences.
@bojanmilicev7781
@bojanmilicev7781 2 года назад
Hey Dave, why do you prefer fetching data in slice instead of in component? What is the pros and cons of both style?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
It is best to abstract your API logic out of components when possible. You can take this a step further when you convert to RTK Query 🚀
@stevereid636
@stevereid636 Год назад
In my experience, I've found it much easier to unit test that way as well
@hardwired89
@hardwired89 2 года назад
thanks you for advance react js tutorial sir
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You are most welcome! 💯
@stevemcqueen2887
@stevemcqueen2887 Год назад
You should describe what a Thunk is more. I had to do some additional reading, and I'm watching youtube because I don't like to read 🤣 Apart from that, excellent course again Dave!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thank you!
@annusingh4694
@annusingh4694 Год назад
Hi Dave! Thanks for this helpful video. Can you please tell how to paginate the posts which we get after fetchPosts async thunk?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're welcome! I have a Pagination tutorial here: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-9ZbdwL5NSuQ.html
@annusingh4694
@annusingh4694 Год назад
@@DaveGrayTeachesCode Awesome! Thank you.
@andreyvasilenko2011
@andreyvasilenko2011 2 года назад
Hi Dave! Thanks for great tutorial. One question. If I update react and react-redux to the current version ("react": "^18.2.0", "react-redux": "^8.0.2"), "posts/fetchPosts/fulfilled" happens twice. How to fix it?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Quick way: Remove strict mode from the index.js. Your issue only happens because the new React 18 strict mode mounts components twice. This only happens in development mode with strict mode enabled.
@fabianceballos6263
@fabianceballos6263 2 года назад
Hi Dave, yours tutorials and skills are amazing, I followed this one but for some reason I'm getting twice the posts and then getting the warning of duplicate key. I downloaded the code and copy paste all the components and still happens. I was wondering if it is about react version (react v18 and react-redux v8).
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you for the kind words, Fabian! I think it must be React 18. If you are using strict mode v18 renders twice.
@moretimeproductions
@moretimeproductions 2 года назад
Had the problem as well, I solved it by instead of .concat the state.posts with the loadedPosts just do state.posts = loadedPosts
@DGAINEprod
@DGAINEprod Год назад
From StackOverflow: React StrictMode calls all Effects twice to make sure their cleanup/unmount handlers work as intended. You may need to change your effects accordingly, even if they have an empty dependency list and would normally not unmount before the site is closed. Note, this only happens in Strict + development mode. In a production build, effects will only be called once and when their dependencies change.
@DGAINEprod
@DGAINEprod Год назад
For additionnal info, consult the React documentation page "Ensuring reusable state"
@hozayves
@hozayves 7 месяцев назад
@@moretimeproductions I had the same problem as well for 5 days but now I solved. Thanks a lot buddy
@yashwanthsrinivas
@yashwanthsrinivas 10 месяцев назад
nice video. thanks
@goodnewsjohn2482
@goodnewsjohn2482 Год назад
You've earned a new subscriber
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Welcome aboard!
@suryasaini1844
@suryasaini1844 Год назад
Hi Dave, Thanks for the tutorial. I have a very sillly question. Why we are not using addNewPost.pending and addNewPost.rejected actions inside extra reducers Similary for fetchUsers we are not using the same pattern.
@ebukachuqz
@ebukachuqz Год назад
Hi Dave, please can I get your opinion on this? For a real big project which would you work with? Redux with redux thunk or Redux-toolkit?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Hello - modern Redux is Redux Toolkit. This tutorial shows the using Redux Toolkit to create async thunks. This should meet your needs. As you progress in this series, you will also learn about RTK Query.
@moretimeproductions
@moretimeproductions 2 года назад
First of all thanks for this great tutorial. I am having a problem towards the end. When I add the payload in AddPostForm to dispatch(addNewPost({ title, body: content, userId })) I get an error that says "Expected 0 arguments, but got 1.", which is strange, because the action should expect the payload as an argument right? I did the tutorial in TypeScript to practise that, but I don't think that the problem is with that. Do you have any idea, why that is? Also when adding a new post whe should add an id at action.payload.id = nanoid(); or else if you add more than one post, they will all have an id of 101, which will cause problems.
@moretimeproductions
@moretimeproductions 2 года назад
Ok, maybe that was TypeScript after all. For anybody, who might have that problem as well, here is how I solved it: We need a payloadCreator. so when we createAsyncThunk for addNewPost, we pass in the "initialPost". This needs a structure, so I set up an interface PostToAdd { title: string; body: string; userId: number; } and then when we pass the initialPost argument, add that type "async(initialPost: PostToAdd). That solved it for me. Thanks again for the great tutorial!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
@@moretimeproductions glad you worked it out! 💯
@stevereid636
@stevereid636 Год назад
@@moretimeproductions Thanks! This worked for e as well 👍🏾
@jiweihe3413
@jiweihe3413 Год назад
Thanks sir, the video is really helpful as always. 7:00 it seems when I include catch error in createasyncthunk(), fetch data is always resolved as Success. Only works by removing the catch inside createasyncthunk.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You are correct! 💯 The source code in the course resources for this lesson was updated to reflect this awhile back. See the previous comment from mohamed youssef for this video. YT has recently introduced a feature where I can note "corrections". Thank you for the reminder - I will add this now correction note now 🚀
@jiweihe3413
@jiweihe3413 Год назад
@@DaveGrayTeachesCode Thank you!
@iedit1713
@iedit1713 2 года назад
good video.... but my when i fetch from api i have been fetching the same content twice some how?? what might be the possible error here? is the key in PostsExcerpt possible error here? that only happens when i use ordered post...with normal post.map() i am not fetching the multiple data
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
If you are using React 18 strict mode, you might experience this. There is an array.concat() in there that doubles the results with the new strict mode behavior.
@leminhdung1981
@leminhdung1981 11 месяцев назад
Thanks!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 11 месяцев назад
Thank you for the support!
@alefe238
@alefe238 Год назад
I was following along with the video and noticed that my store duplicated the data that comes from the api. Any idea of why this is happening? Incredible video btw
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thanks! Yes, the duplication is due to React 18 strict mode and the use of concat. This tutorial was created with React 17. Other comments on this as well. Create a new array with the spread operator instead of concat.
@jritzeku
@jritzeku Год назад
Would this redux code/structure be same once we incorporate a backend like Express js or even Firebase? For instance, I've seen API calls generally be made in a component like PostList or else in a custom hook like useFetchCollection. However in this example, we are handling such tasks in our slices, which then makes lot of the uses cases for custom hooks not really worth it anymore.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
This is one way to do it. If you keep going in this series, you will see an RTK Query implementation that generates its own hooks, too.
@jritzeku
@jritzeku Год назад
@@DaveGrayTeachesCode IS there one you prefer/recommend? Im assuming using RTK query would be preferred since it offers performance benefits. Man...redux jus tkeeps changing haha.
@danieljing9319
@danieljing9319 2 года назад
informative and clear
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Glad to hear that! 💯
@caraxes
@caraxes 2 года назад
Hi great video. When you have in plan something about redux saga with slice's?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
I need to get through the redux toolkit basics first 🚀
@DeepakGupta-pz4fx
@DeepakGupta-pz4fx 2 года назад
@@DaveGrayTeachesCode redux saga using fetch api data implementation
@okumorphilip8087
@okumorphilip8087 Год назад
Hello Dave, i hope this meets you well, I'm having a little challenge with this chapter, when i fetch my data from the typicode API, each post appears twice, and the top post is always inactive, because, when i use a reaction button on the one on top of the similar post, the reacton count does not respond on the first post, but the reaction counts are updated for the second one and not the first one, when i add a new post, it always goes 2nd, because like i said the first post of the similar post that loads with the app when it starts, looks inactive and doesnt even repond to any clicks
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Getting duplicate posts is likely due to the concat() in the store.js - This tutorial used React 17 but now, with React 18 in dev mode, each component is mounted twice. Instead of concat, create a new array with brackets and spread in the values [...values]
@okumorphilip8087
@okumorphilip8087 Год назад
@@DaveGrayTeachesCode Oh, Bless You Dave. Thanks.. When i land my first job, i will buy you Pizza.
@baselinereviews
@baselinereviews 11 месяцев назад
I have a question, but this may be due to react 18 rather than a redux issue. I wanted to have the posts load when the component was loaded, so I moved the dispatch statement to the component itself and put the dispatch statement inside of a useEffect. However, I noticed that when I did this that now the redux action fires twice. Upon some more reading, this is because react now unmounts and remounts the component to help devs look out for remountable components when in dev mode. If I remove the React.strictMode tags, the redux action no longer fires twice. Is there a way to prevent this behavior? Or is this why in your videos you load the state upon loading the application?
@baselinereviews
@baselinereviews 11 месяцев назад
Ok I found an answer to this and it would be, upon the cleanup of a component, if the promise returned from the dispatch() function is not yet fulfilled, call promise.abort() to abort the calling of the thunk, however, I feel that there has to be a better way
@razmiqayelyan1497
@razmiqayelyan1497 2 года назад
Thanks a lot
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome, Raz! 🙏
@micharozek3046
@micharozek3046 2 года назад
Man you're talking the same as Hershel Greene from the Walking Dead xD Thx for the vid! :)
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
I hadn't heard that comparison before! I'm nowhere near that old, but Hershel was great on that show 💯
@maxwellalexander6474
@maxwellalexander6474 Год назад
¡Gracias!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thank you for the support! 💯
@yt-sh
@yt-sh 2 года назад
Hello Dave, awesome video. Can we get RTK Query next?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
That is coming soon! 💯🚀
@yt-sh
@yt-sh 2 года назад
@@DaveGrayTeachesCode Awesome, really appreciate it! Btw I tried but couldnt understand, can you tell me what is the core reason for the usage of builder in RTK?
@yogendra591
@yogendra591 Год назад
Any idea, do we need to test the createAsyncThunk separately while testing the createSlice in Redux toolkit?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
This may help: stackoverflow.com/questions/67087596/jest-testing-createasyncthunk
@dharmendrasharma1445
@dharmendrasharma1445 2 года назад
Hi Dave, thanks for great video, in React 18 , API is calling twice so we are getting one error ' Encountered two children with the same key, ' it's not happening in React 17
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
It is happening in React 18 with Strict Mode enabled. The new strict mode mounts, unmounts, and then mounts components again. This will be from the useEffect in PostsList.js in this lesson. Discussing this change and others from React 18 here: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-N41B_SVdzwg.html ...A solution is to keep moving on in this series until you eventually switch over to RTK Query that removes this type of logic from useEffect.
@dharmendrasharma1445
@dharmendrasharma1445 2 года назад
Thanks, Dave Gray for your support
@dilucsuki8470
@dilucsuki8470 Год назад
20:40 even tho the canSave looks better it's not as good as it was, since it creates another execution context, would be perfect with just title && content && userId && addRequestStatus==="idle"; :D lovely tutorial + loved the extra POST example
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thanks!
@tzCraig
@tzCraig Год назад
Thanks, Dave! You're saving my life here... #codingBootcamp 😰
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Right on!
@solution001
@solution001 Год назад
Could you make an Lit Webcomponents + Redux-Thunk. I use it, and could help if you need it.
@ougininja8412
@ougininja8412 Год назад
Amazing video
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thanks!
@samislam2746
@samislam2746 2 года назад
I have a question, I saw you wrote dispatch inside the useEffect() array at line 17 inside react_redux_toolkit/03_lesson/src/features/posts/PostsList.js ` useEffect(() => { if (postStatus === 'idle') { dispatch(fetchPosts()) } }, [postStatus, dispatch]) ` what does that mean? isn't dispatch a function? how React is going to know that the dispatch function was changed? it doesn't change, it fires. What If I removed that dispatch from here? what are the downsides? And thank you 😁
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
No real downsides I can see other than a possible warning in the console. 💯
@samislam2746
@samislam2746 2 года назад
@@DaveGrayTeachesCode 👍
@sonamohialdin3376
@sonamohialdin3376 2 года назад
Awesome tutorial
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Glad you liked it, Sona! 💯
@sonamohialdin3376
@sonamohialdin3376 2 года назад
@@DaveGrayTeachesCode You are welcome thank you
@prakashbanjade4374
@prakashbanjade4374 Год назад
As I refresh the page when I am in SinglePost (say /posts/5), I get error as post not found (my custom error if post not found by id). Why? Other things work fine. I can navigate to specific post as I click on visit post but refreshing this page is causing error. I tried logging out the posts in SinglePost component and it is empty
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
This is a single page app (SPA) as all React apps are. When you refresh the page, you lose your client-side state. It's like restarting an app.
@joaoalegria7578
@joaoalegria7578 Год назад
Can this be implemented ina Next.js project normally or do I need to use the Next js wrapper?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
I am planning to cover Next.js soon. Next.js is server-side.
@joaoalegria7578
@joaoalegria7578 Год назад
@@DaveGrayTeachesCode Awesome! Yeah I know, I'm currently building an application in react next.js and redux tool kit, that's why I asked. lol I've never used next.js and redux tool kit so I'm still pretty green. Just subbed and my notifications are on! Cheers
@AbuTaher-vx2oe
@AbuTaher-vx2oe Год назад
if i follow like your tutorial createAsync thunk error also entered fullfiled
@antonioscaravilli9966
@antonioscaravilli9966 2 года назад
I will love to watch this video
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you, Antonio! 🙏
@dharmeshgohil9375
@dharmeshgohil9375 2 года назад
Awesome👍👍👍😊
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you 🙏
@CarlosSuarez-mc3is
@CarlosSuarez-mc3is Год назад
For some reason my extra reducer is not catching the error. I tested error handling and the case for rejected never gets trigger. Looking at the thunk function, I can see that it does catch the error. I'm not sure what could be wrong here. Could you advise what could be the potential issuel
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
I can only guess from here. Compare your code to mine for differences. The source code is available at the course resources link in the description.
@CarlosSuarez-mc3is
@CarlosSuarez-mc3is Год назад
@@DaveGrayTeachesCode sure, but I also comprare it to the documentation and nothing seems different. I might have added a Middleware km the rootreducer, but how would this change the hook? :O
@wasimdorboz
@wasimdorboz Год назад
you best teacher in the world 😁😁
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thank you for the kind words!
@TheSesameStreetGang
@TheSesameStreetGang 2 года назад
Great video as always but why would you not create a seperate reactions object and add that everywhere it is needed? It would dry up your code a lil!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
The reactions data is an object, but I may be missing your suggestion here? Are you thinking a separate slice for reactions? That would create more code. I kept them with the posts state because they are part of the posts. In addition, I based this on the official docs example (gave credit at beginning of video) and you can reference that structure here: redux.js.org/tutorials/essentials/part-5-async-logic
@TheSesameStreetGang
@TheSesameStreetGang 2 года назад
@@DaveGrayTeachesCode Hey, I just meant like an object lookup like this: const reactions = { thumbsUp: 0, wow: 0, heart: 0, rocket: 0, coffee: 0, }; At the top and then whenever they are needed within the slice you can just do something like: prepare(title, body, userId) { return { payload: { id: nanoid(), title, body, userId, reactions, date: new Date().toISOString(), }, or const loadedPosts = action.payload.map((post) => { post.date = sub(new Date(), { minutes: min++ }).toISOString(); post.reactions = reactions; return post; }); Since we're using the same object in multiple places, if we want to make a change we can just make it to the first object and it will change in multiple places in the slice.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
@@TheSesameStreetGang I see what you're saying 🙏 Yes, this would work where I had to populate the data that was not really in the fake API 💯
@neelpatel8309
@neelpatel8309 Год назад
dave in my code the postlists is rendering twice and it giving duplicate key error is there anyone who faced the same problem ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Likely due to React 18 strict mode. Some have solved this (possibly in these comments) by removing the concat() for the store posts and replacing it with a new array using the ... spread operator. This tutorial was made with React 17, but in React 18 strict mode (only applies to dev mode), all components are mounted twice.
@ericmomoh7927
@ericmomoh7927 Год назад
Nice content and teaching. Please help us how to connect it to firebase firestore and get data from firestore using redux thunk. Thanks for the tutorial it amazing
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're welcome! 🙏 And thank you for the request!
@ericmomoh7927
@ericmomoh7927 Год назад
Glad I found your channel
@SL4UGHT3R
@SL4UGHT3R Год назад
13:50 why dispatch is a dependency in useEffect dependency array?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
As recently as React 17, you would receive a warning if it wasn't. It is a function and likely does not change. With React 18 you should not receive a warning if left out.
@SL4UGHT3R
@SL4UGHT3R Год назад
@@DaveGrayTeachesCode ok, thanks!!
@roberainsarmu8135
@roberainsarmu8135 Год назад
I am trouble in getting the source code for code debugging. please can u post github link on description? thank u
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
There is a link to the course resources which includes source code in the description. On the course resources page, each chapter of this series is linked to with source code available.
@mohamedyoussef8835
@mohamedyoussef8835 2 года назад
Awesome Tutorial +++++++++++++++++++++++
@kamelkamatchu8830
@kamelkamatchu8830 2 года назад
thank you for this great tutorial but if you run this in react 18 will get an 100 warning of two children with same key and also blogs are dublicated in page but in react 17 there is no error
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
React 18 has made some changes. One is rendering twice in strict mode. Not sure this would be the cause but thought of that first.
@moretimeproductions
@moretimeproductions 2 года назад
Had the problem as well, I solved it by instead of .concat the state.posts with the loadedPosts just do state.posts = loadedPosts
@kamelkamatchu8830
@kamelkamatchu8830 2 года назад
@@moretimeproductions thanks for your comment i also solve it with hook useRef
@moretimeproductions
@moretimeproductions 2 года назад
@@kamelkamatchu8830 How did you approach that?
@kamelkamatchu8830
@kamelkamatchu8830 2 года назад
@@moretimeproductions youtube always delete my comment with link .. and as Mr Dave comment react 18 render two times in strict mode and react team already propose solutions for this
@Xtapodi27
@Xtapodi27 2 года назад
What is your color theme please?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
GitHub theme 🚀
@belginefe1838
@belginefe1838 2 года назад
Hi Dave, thanks for great tutorial, I hava a question. I try to write second parameter of thunk ( which is a function) in another file and import this function in slice file. Like : import {fetchPosts, createPost} from './api'; const fetchData = createAsyncThunk('posts/getPostsAsync', fetchPosts()); If I do that, for the post operations how can I pass the newPost parameter on this asyncThunk function? const createPostsAsync = createAsyncThunk('posts/createPostsAsync', createPost(newPost));
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
If you look at the addNewPost async thunk example in this video (and my source code), you should see an example of a function receiving a parameter named initialPost. While this example uses an anonymous function, you should be able to use a previously created async function which I assume is what your createPost function is.
@inamulhassan4384
@inamulhassan4384 2 года назад
I was following the playlist form the beginig awsome content. 🙌 I got an error when i import the axios lib Compiled with problems:X ERROR in ./node_modules/axios/lib/adapters/xhr.js 17:10-24 Module not found: Error: Can't resolve 'url' in 'D:\Personal edux-toolkit\code ode_modules\axios\lib\adapters' BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { "url": require.resolve("url/") }' - install 'url' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "url": false } I'm using react 18 any idea ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
This line is the problem. It cannot find what it is looking for in your node_modules directory where you packages are stored: Module not found: Error: Can't resolve 'url' in 'D:\Personal edux-toolkit\code ode_modules\axios\lib\adapters' Did you add axios to your project by typing: npm i axios ...at the command line?
@inamulhassan4384
@inamulhassan4384 2 года назад
@@DaveGrayTeachesCode yes
@inamulhassan4384
@inamulhassan4384 2 года назад
@@DaveGrayTeachesCode This problem exist with axios 0.27. Downgrade to 0.26 worked for me
@stevereid636
@stevereid636 Год назад
@@DaveGrayTeachesCode Axios 0.27.2 also works👍🏾
Далее
Redux Middleware/Async/Thunk: The complete Guide
1:06:03
Every React Concept Explained in 12 Minutes
11:53
Просмотров 479 тыс.
Programming Is NOT Enough | Add these 7 skills…
13:19
You might not need useEffect() ...
21:45
Просмотров 154 тыс.
Async Thunks in React Redux Toolkit with TypeScript
12:36
State Managers Are Making Your Code Worse In React
13:33