Next.js 13 Crash Course Tutorial #6 - Fetching & Revalidating Data

Net Ninja · Beginner ·🌐 Frontend Engineering ·2y ago

Key Takeaways

Shows how to fetch and revalidate data in Next.js 13

Full Transcript

okay then so now we know all the basics Pages routes layouts links images and styles next I want to move on to fetching data that we can then show on the tickets page which is currently completely empty so to begin with we need somewhere to fetch the data from now that could be any API endpoint or even a database directly because remember any component that we make inside the app directory is a server component by default so we can put server logic inside this component if we wanted to and not have to worry about that code ever running in the browser for the sake of this lesson though I'll just be using a local Json file as some dummy data and then I'll use the Json server package to wrap that in API endpoints so that we can interact with it as if it was a real API for production you wouldn't do this obviously you'd either use a real API or your own database or something else but the methodology and the way we're going to fix the data would be pretty much exactly the same so it's okay for this sample project right now all right then so I've already created an underscore day data folder right here in the root of the application and inside that is a Json object with a property called tickets which is an array of objects where each object represents a single ticket and each ticket has an ID property it has a title property a body property and also a user email property as well and we have three of those in total and by the way if you want to grab this Json you can do from the course repo the course finals the link to that is going to be down below the video you just need to select the lesson 6 Branch from the drop down and then you can copy it so that's our data now we need to run Json server and tell it to watch this file so in order to do this you need to have Json server installed globally on your computer and to do that you can open up any terminal and then type npm install Json hyphen server and then a space and then hyphen G to install it globally on your computer once that's installed you can use it by typing jsonhyphen server the sbase then Double Dash watch and then Double Dash Port 4000 and then we want the path to the Json file that we want to watch which is dot forward slash then in our case underscore data and then it's forward slash the name of the file name which is db.json and when you press enter that's going to spin up a server and create endpoints for first to interact with this tickets resource and you should see the end point in the terminal and if you view that end point in the browser localhost Port 4000 forward slash tickets now we can see that our array of data that we get back awesome so that works now we want to fetch this from our tickets component so then we could make a fetch request directly from the page component which is a server component remember and the way we do that is just by using the standard fetch API which is made available to us however just for the sake of keeping things tidy modular and reusable I want to create a new component inside this tickets directory called ticket list and it's inside this component that I want to fetch the tickets data and output it inside the template and remember all components inside the app folder are server components by default including this one it's not just page components it's any component we make so the way we fetch the data inside here is just the same as the way we'd fetch it from inside the page component now when we're using server components we can declare them as async functions and use the fetch API directly inside them which is awesome so I could put the async keyword right in front of this component to make it an async one and then down inside the component I could use the fetch API to go out and fetch the data however what I like to do instead is make another function outside the component which is responsible for fetching the data so that all the fetch logic is kept outside the component itself to keep things a little bit cleaner so let's do that let's make another async function up here and let's call this something like get tickets and it's inside this function that we want to go out and fetch them so let's do that then let's say const response is equal to a weight Fetch and then we want to paste in the end point which is localhost Port 4000 forward slash tickets which remember is coming from Json server this is the end point it gave us for the tickets resource now we can grab the data from that response by saying response.json and that returns a promise because it's asynchronous and in fact we're going to return this from the function so now when we call it down here I could say const ticket which is the tickets data the tickets array is equal to get tickets but because this right here returns a promise I need to await the return for that so I can say ticket is equal to and wait get tickets and remember we can use a weight because we can have asynchronous components right here all right so now we have that tickets data let's work on the template so we'll do a fragment first of all which is just an empty tag basically and then inside here we want to do something Dynamic we want to map through tickets and return a bit of template for each one so all we need curl the braces and then say tickets dot map we fire a function for each ticket and we return a bit of template for each ticket inside parentheses now each time we fire a function for a ticket we get access to that ticket and then down here we need to return some kind of element to wrap the rest of the template so we'll do a div tag and that parent element must have a key prop when we map out through some data in react so we'll say key is equal to ticket dot ID because we do have an ID property we have ID title body priority and use email all right so we also want to give this a class name or card and we already made that class remember in one of the previous lessons and then also we'll give you some extra margin in the y direction by using a Tailwind class ny5 now inside this div I want to Output the title the body and the priority so first of all the title inside an H3 will say tickets dot title and then below that we'll output some of the body but not all of the body so I'm going to say tickets dot body and then use the slice method to slice a string from position zero to position 200. so essentially the first 200 characters and then after that we'll do dot dot dot to signify there is more and then after that we'll do a div now this is going to have a class name equal to pill in fact this needs to be dynamic so what I'm going to do is Curly braces and then a back text ring so we can output a variable and it's going to have a class of pill but also I want it to have a class of whatever the priority is so that could be low it could be medium it could be high now remember in our CSS we had those classes down here somewhere so pill dot medium pill dot high and P Dot Low and it just colorizes them differently so I want to Output the tickets priority property inside a variable so dollar sign curly braces and then say ticket dot priority like so that's going to be low medium or high alright so inside here we can output the ticket priority so ticket dot priority and after that I will do priority so it will be either low priority high priority or medium priority okay and I think that's pretty much it what I am going to do also is check to see if we don't have any tickets so if tickets dot length is equal to zero then I want to output something so we'll do double ampersand and then parentheses so if this evaluates to true then this side runs and therefore outputs some template so we'll do a paragraph tag inside here and that will have a class name equal to text open Center and then we'll just say there and no Open tickets yay all right then so now we're fetching the data we're returning the data we're using that function to get the tickets data and then we're mapping through the tickets inside this component and then we'll be able to view them in a browser now before we try this in a browser we need to put this component ticket list inside the tickets page so let's do that underneath tickets in fact what I'm going to do first of all is just alter the template of this a little bit I'm going to create a nav because we'll use a nav at the top of this page later on inside data div and then we'll do our H2 which says tickets and then below that I'm going to do a little paragraph tag with a small tag inside that and then we'll just say currently open tickets like a little subtitle okay so now beneath the navigation we want to Nest that ticket list so let's say tickets list like so it's going to Auto Import it for us up here cool so now this should all work all right so I'm on the dashboard but if I go to view the tickets then we should see a list of all the tickets which we do awesome so we can see the title for each one we can see a bit of the body but just a bit of the body not all of it and also the priority and this is all looking pretty nice because we already added all those Styles in in a previous lesson but now we know that this is work with fetching the data and we're showing that in a browser awesome now remember all of this fetch logic is running on the server because this is a server component by default so by the time the page reaches the browser the data has already been fetched and output into the template also by default next.js13 does two things for us when it comes to fetching data first of all it dedupes any fetches that we make to the same resource and that means that if we fetch this ticket status somewhere else in the application as well as here next will only actually fetch the data once and then it will reuse the data it gets back wherever else we call that fetch secondly it caches the response of any fetches that we make so that if we navigate away from the page and then come back sometime later it uses the cached version of the data it already fetched and it does that indefinitely which is great for site speed great for user experience because the page is going to load instantly and a lot of the time that's probably the behavior that you want for your website or maybe your data responses don't change over time much but there are times when you probably don't want to aggressively cash your fetches indefinitely for example like our application where the data might change very very frequently as users add more tickets or maybe for a new site where articles might get added several times a day so in those cases you can ask nextgis to revalidate the cache data which basically means refetch it and rebuild the page that uses that data and we can ask for it to do this after a set amount of time for example where content might change every few minutes you could ask it to revalidate every 60 seconds or less if the content only changes every other day you might ask it to revalidate the data about every 24 hours or something now the way we do this is by adding a second argument to the fetch function which is an object and then one of the properties on the object is going to be called Next which should also be an object and inside that object we have a revalidate property and we set that equal to the amount of time that next should wait since the last page visit before revalidating the data again and if another request for that page comes in then it will show that revalidated data that refetch data okay so for example I could set this to be 30 and that would mean if I visit the page for the first ever time next would fetch the data from scratch right then if I visit the page within 30 seconds again it will serve the data up from cash but if I visit the page again after that 30 seconds then next.js is going to attempt to refetch the data again in the background however even then I'm still going to get served the previously cached data because it still has that available when I made the request but the next time I visit I will see the updated data so let's give this a whirl and see if it works alright so I've got to open the website on the right and the code on the left and what I want to do is first of all just refresh this page to make a new request to the page so now the 30 seconds Starts Now what I'm going to do is quickly delete this id21 right here so let me cut that and then save it now what I'm going to do now is refresh again over here now within the 30 seconds so nothing's going to happen it's all still the same and it's not even going to trigger another refetch in the background because since the initial fetch it's not been more than 30 seconds until my next one does that make sense so what I'm going to do is just wait for about an extra 10 seconds now all right and then I'm going to refresh the page again but nothing should change this time if I refresh we should say nothing has changed even though we've gone over the 30 seconds and that's because we have gone over the 30 seconds so in the background when we made that next request next we'll try to fetch the new data but because it already had the previous data in Cache it served it to us but now in the background it's revalidated this so the next request we make now is gonna show the updated data where this one shouldn't be here so let's cross our fingers and refresh again and hopefully we can see yep now we just get two of them awesome so then that's how we can fetch data from a server component and also revalidate the cache data based on a certain time frame now actually for the project that we're making I don't want nexjs to ever serve up data from Cache because I feel like on a help desk tickets could be constantly being added and updated maybe every minute or so and some of them could be really urgent so to opt out of the data being cached at all you can set this value to be zero and when this is zero the data will never be cached and it will always be fresh it does however mean that it might be slightly slower because refetching data every time is obviously not as quick as serving data from cash but let's keep this at zero for now and try this again so I've got the project open again on the right and you can see if we refresh we still have just the two tickets and now what I'm going to do is go back to db.json undo that cut that I did to put in this ticket again and then because we have revalidated set to none if we refresh straightway it's going a retry to fetch the data because it's not serving from cash anymore and we can see we get three tickets again awesome

Original Description

In this Next 13 tutorial series, you'll learn the basics of Next.js to make a simple project, using the new app router & server components. 🚀🥷🏼Access the entire Next.js 13 Masterclass course on Net Ninja Pro: https://netninja.dev/p/next-13-masterclass ➡️ Use promo code NEXTNINJA50 for 50% off! 📂🥷🏼 Access the course files on GitHub: https://github.com/iamshaunjp/nextjs-masterclass 📂🥷🏼 CSS File from course files: https://github.com/iamshaunjp/nextjs-masterclass/blob/lesson-43/app/globals.css 💻🥷🏼 React Tutorial: https://netninja.dev/p/build-websites-with-react-firebase 🔗🥷🏼 Next.js docs - https://nextjs.org/docs 🔗🥷🏼 CSS modules in Next.js - https://nextjs.org/docs/app/building-your-application/styling/css-modules 🔗🥷🏼 VS Code - https://code.visualstudio.com/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Net Ninja · Net Ninja · 0 of 60

← Previous Next →
1 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

Related Reads

📰
I Built a 100% Free, Frictionless Resume Builder with Direct PDF/Word Exports
Learn how to build a free and frictionless resume builder with direct PDF and Word exports, and discover the tools and techniques used to create it
Dev.to · Solangi Waqas
📰
How to Deploy Angular SSR on Cloudflare Workers for Free — No VPS, No Fees, No Credit Card.
Learn to deploy Angular SSR on Cloudflare Workers for free without needing a VPS, fees, or credit card
Medium · JavaScript
📰
How I Added Browser-Based HEIC to JPG Conversion (No Server, No Upload)
Learn how to convert HEIC to JPG in the browser without server upload using heic2any
Dev.to · Rushikesh Lade
📰
Angular Signals in 2026: From Fundamentals to Architect-Level Patterns
Learn Angular Signals fundamentals and architect-level patterns to improve your Angular applications
Dev.to · Amanulla Khan
Up next
Elementor Angie Ai Plugin Tutorial
Quick Tips - Web Desiign & Ai Tools
Watch →