Understanding how to use Next.js with App Router
If you are interested in web development and want to work with a modern framework, Next.js is a great choice. This framework provides you with the ability to create high-performance websites using React. One of the attractive features of Next.js is the App Router, which can help you organize your applications more systematically and accessibly.
When talking about Data-fetching, Next.js comes with powerful capabilities like Server Actions and Mutations. These capabilities allow you to retrieve information in a standard manner while receiving high-performance data from the server and make modifications. Now, let’s examine how to utilize these capabilities.
Server Actions enable you to write code for the server side directly within your React components. In fact, you can write functions that obtain information from the API and use that information to update your website UI in real-time. This process results in faster and better page rendering.
On the other hand, Mutations allow you to update existing data without needing to reload the page. By using Mutations, you can change current data and reflect those changes to the user without requiring a page refresh. This point greatly enhances the user experience.
Now, let’s take a look at a code example to better understand how to implement Server Actions and Mutations.
// Example of Server Action
export async function getData() {
const response = await fetch('/api/data');
const data = await response.json();
return data;
}
// Example of Mutation
export async function updateData(id, newData) {
const response = await fetch(`/api/data/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newData),
});
return await response.json();
}
Explanation of code examples
Code: export async function getData() { ... }
This function defines an asynchronous operation that utilizes an API to retrieve data.
Line: const response = await fetch('/api/data');
Using the fetch method, we pull data from the endpoint of our API.
Code: return data;
Finally, we return the retrieved data as the function output.
Code: export async function updateData(id, newData) { ... }
This function is designed for updating data and performing an asynchronous operation.
Line: method: 'PUT'
This specifies the HTTP method for updating data using a PUT request.