All of these dishes look so tasty! What if we could add some of them in a shopping card?
Next, we create a new component named Cart.js:
To keep track of our items added to our cart across pages we will use the React Context API. Context will allow us to manage the state of items in a provider component that will be re-used on the checkout page. The only thing React Context will not take care of for us is saving items on a page refresh, for that you would want to save the items to a cookie and restore the items from the cookie. I will work to implement this soon if requested.
The items are currently saved to a cookie called items, but the items are not restored on refresh.
Create a new directory inside our components folder:
Note: you can name your AppProvider anything related to the context you are storing (i.e. ItemsContextProvder). This would allow you to use and keep track of multiple providers/consumers throughout the app if your needs grow.
Now we will need to make some changes to use our Context throughout the application and on the dishes page.
Update the _app.js and /pages/restaurants.js files to use the AppProvider/Consumer components:
Now if you refresh the page you should see the Cart component to the right of the dishes.
Your Layout header should also update with the username of the logged in user and show a logout button if you are logged in.
To actually place an order the isAuthenticated prop must pass to true, in a real world app you would want to secure these routes on the server side rather than on the client side. Any props/state on the client can be altered and therefore should not expose real world data without server validation.
For the sake of the tutorial we are not currently implementing this.