![]() The useSelector hook takes a function (selector). To get data from Redux store, we use the useSelector hook from the react-redux package. So we need a way to get the diet value from the store and also update it. If user clicks on the Veg Only checkbox then we need to only show the vegetarian items. Let’s look at how some of these things are done - Diet Toggler Get the loaded menu from Redux store and pass it to MenuList component.Pass the API status to Message component so user is notified when API is done loading.Read the diet from store and update it when user toggles the Veg Only checkbox. ![]() The whole file is doing the following stuff. The App.js file is our top most parent component React renders. ![]() Integrating store from redux.js to index.js App.js file Then in index.js, we create a store, wrap the App component inside Provider component from react-redux package and pass the store as a prop to the Provider. We also enable the Redux DevTools extension for better debugging and then export this function. We make a function in which we create a Redux store, pass the foodReducer to it. Then we find the item’s quantity in cartByIds, change it by 1 and again store it. When user adds an item to cart, the dispatched action gets that item’s id in payload. We store data (quantity etc.) for each item by its id inside cartByIds. Similarly, we have implemented ADD_TO_CART and REMOVE_FROM_CART. Return the new state with changes in menuById and menuIdList.Make an array of ids for only veg items.Traverse the menu array and store each item by id in menuById object.We put this array into our store like this. When LOAD_MENU is dispatched, it’ll send an array of food items in the menu key of payload. Now let’s write the logic for CHANGE_DIET action in the reducer. We’ll cover this when we talk about selectors. The only downside is that we can’t just directly show data of store to user we’ll need to do some pre-processing to mold the data into the shape the various views requires. Similar to this cartByIds only store a mapping of item id and its quantity. We can cache the food item ids per diet so that when user selects a diet again we can pick the ids from cache instead of making an API call. Filter results get cached - Suppose we get the items for a diet via an API call.Faster item access - Since we’re storing stuff by id, if we know the id accessing it will happen in O(1) instead of digging through an array which in best case scenario is O(log n).Reduce duplicate copies - If we had stored data directly in arrays then some food items would be duplicated in both all type and veg type.There are three main benefits of storing data this way. The menuIdList array only contains a list of ids per diet. You’ll notice that the actual data about each food item is stored by its id in the menuById key of the store.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |