Here's the 7th and the final blog in this series, concluding our journey of building a Full Stack Web Application using Next JS.
Till now, I have uncovered the secrets of implementing backend with Next JS and performing User Authentication & performing CURD operation on Data using MongoDB, Fetching the data to frontend.
In the previous blogs , I have provided the steps to setup Next JS project from scratch. Do check them out if you want to learn next.js from scratch!!
What's Coming up โฉ:
Filtering out the Data based on selected Options.
Uploading final project code to GitHub
Deploying the project to Vercel.
Before starting up, let me introduce myself ๐ฆ๐ผ
I'm Sujal Soni, a 3rd Year B.Tech. student in CSE who is a dedicated Full Stack Web Developer proficient in technologies like Node.js, Express.js, React.js, MongoDB, Firebase, Next JS. With a passion for problem-solving and attention to detail, I've successfully completed various projects. Eager to contribute to innovative projects and collaborate with talented teams to drive impactful solutions.
You can connect with me on LinkedIn as well as on Twitter ๐จ๐ผโ๐ป
If you are following this series from the start, then I'm sure that you have already implemented and understood important bits of next.js project setup.
Viewing this blog series for the first time? Start from Blog 1 taking the best out of this series.
Now as we are already done (Check previous blogs) with the setup our User Data Model and User Data Routes inside next.js to handle Image as well as text feature in our Next JS project, lets further make some additions to the dashboard page code to filter out the data.
Code Reference:
Refer to my GitHub Repository to access the updated code and take reference:
github.com/Sujal-2820/Full-Stack-Web-Applic..
Step 1:
Updating Dashboard file (src/app/dashboard/page.js
):
Here we specifically need to focus on Column 1 that we previously made
If you remember we had setup certain selection inputs and options like this:
First of all set 2 new state variables:
const [userData, setUserData] = useState([]);
const [selectedCategory, setSelectedCategory] = useState(""); //new state variable for category selection
const [sortBy, setSortBy] = useState(""); //new state variable for sort option selection
Add 2 new functions to handle the selection change:
const handleSortChange = (event) => {
setSortBy(event.target.value); // Update only sortBy state
};
const handleCategoryChange = (event) => {
setSelectedCategory(event.target.value); // Update selectedCategory state
};
Add an "onClick" Event Listener to the button Show Filtered Data
:
<Button onClick={handleFilterData}>Show Filtered Data</Button>
Add a function namely handleFilterData:
const handleFilterData = async () => {
try {
const response = await axios.get("/api/userData"); // Fetch raw data
const { userData } = response.data;
console.log(userData);
const formattedData = await Promise.all(
userData.map(async (data) => {
const imgs = await listAll(
ref(imageDb, `dataImages/${data.imageUrl}`)
);
console.log("Image reference: ", imgs);
const urls = await Promise.all(
imgs.items.map((val) => getDownloadURL(val))
);
console.log(urls);
const imageUrl = urls.length > 0 ? urls[0] : "";
return { ...data, imageUrl };
})
);
let filteredData = formattedData; // Initially set to all data
// Apply category filtering if selectedCategory exists:
if (selectedCategory) {
filteredData = filteredData.filter(
(data) => data.category === selectedCategory
);
}
// Apply sorting based on sortBy:
const sortedData = [...filteredData]; // Create a copy to avoid mutation
sortedData.sort((data1, data2) => {
const date1 = new Date(data1.date);
const date2 = new Date(data2.date);
if (sortBy === "newest") {
return date2 - date1; // Newest to Oldest
} else if (sortBy === "oldest") {
return date1 - date2; // Oldest to Newest
}
return 0; // No sorting if sortBy is empty
});
setUserData(sortedData); // Update state with filtered and sorted data
} catch (error) {
console.error("Error fetching user data:", error);
}
};
This function accepts the values of the filter options (category and sortBy) and implements the logic to check for these parameters in the existing list of data.
If the data matches with the parameters mentioned, it simply returns an array of the matched dataset.
Here is the snippet to show how a filtered data would look like:
Step 2:
Uploading the project files to GitHub.
Here's a step-by-step process to create a GitHub account and push your code from VS Code to a GitHub repository:
1. Create a GitHub Account:
Go to https://github.com/ and click "Sign up" in the top right corner.
Fill out the signup form with your username, email address, and a strong password.
Verify your email address by clicking the link sent by GitHub.
2. Install Git (Optional):
While GitHub operates online, you can also use Git version control software locally for better workflow.
If you don't have Git installed, download and install it from https://git-scm.com/downloads for your operating system.
3. Create a New Repository on GitHub:
Log in to your GitHub account.
Click the "+" icon in the top right corner and select "New repository."
Give your repository a descriptive name (e.g., your-project-name).
Optionally, add a short description of your project.
Choose whether to initialize the repository with a README file (recommended).
Click "Create repository."
4. Initialize a Local Git Repository in VS Code:
Open your project folder in VS Code.
Open the integrated terminal in VS Code (Terminal > New Terminal).
Run the command
git init
to initialize a Git repository in your project folder.
5. Create a Local README File (Optional):
If you didn't choose to initialize with a README on GitHub, create a new file named "README.md" in your project folder.
Add a descriptive title, project description, and any other relevant information you want users to see about your project.
6. Add and Stage Files for Version Control:
Use the
git add
command to stage files you want to track in your Git repository. Examples:git add .
(adds all files in the current directory)git add src/app/dashboard/page.js
(adds a specific file)
After adding files, run
git status
to see which files are staged and unstaged.
7. Commit Staged Changes:
Run the
git commit
command to create a snapshot of your staged files with a descriptive commit message. Example:git commit -m "Added dashboard page component"
8. Connect Your Local Repository to GitHub (Optional):
In your terminal, run the following commands to set up the remote repository URL:Bash
git remote add origin https://github.com/YOUR_USERNAME/your-repository-name.git
Use code with caution.
content_copy
Replace
YOUR_USERNAME
with your GitHub username andyour-repository-name
with the actual name of your repository.You can verify the remote URL with
git remote -v
.
9. Push Local Commits to GitHub:
Run the
git push origin master
command to push your local commits to themaster
branch of your remote repository on GitHub.- The first time, you may be prompted to enter your GitHub username and password.
Subsequent Pushes:
- Once you've connected your local repository to the remote repository, follow steps 6 and 7 (adding/staging and committing changes) and simply run
git push origin master
to push your new commits to GitHub.
Step 3:
Deploying your project on Vercel:
I would recommend watching this video on YouTube to take an easy reference to deploy your project on Vercel. Refer to the following link ๐๐ผ
https://youtu.be/2HBIzEx6IZA?feature=shared
Take a look at my hosted project on vercel: https://nextjs-full-stack-web-application.vercel.app/
Well Done ๐, you have successfully implemented all the CRUD operations inside the Next JS project using routes and model and have successfully Hosted your website.
In case of any doubt, you can reach out to me via LinkedIn ๐จโ๐ป
You can also connect with me on various other platforms like Twitter, GitHub
If you liked this Blog, make sure to give it a ๐ and do Follow me on this platform to get notified for my next blogs in this series.
Happy Coding!! ๐จโ๐ป