Skip to content

Commit

Permalink
Feat: Finished edit links
Browse files Browse the repository at this point in the history
  • Loading branch information
xSankalpaD committed Sep 7, 2024
1 parent a54d190 commit 13c5bca
Show file tree
Hide file tree
Showing 7 changed files with 211 additions and 33 deletions.
9 changes: 9 additions & 0 deletions node_modules/.package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 11 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"express": "^4.19.2",
"jwt-decode": "^4.0.0",
"lucide-react": "^0.439.0",
"next": "^14.2.8"
"next": "^14.2.8",
"tailwind-merge": "^2.5.2"
}
}
19 changes: 18 additions & 1 deletion server/controllers/loadPrevious.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const User = require("../models/user");
const jwt_decode = require("jwt-decode");
const jwt = require("jsonwebtoken");

//jwt_decode does not work anymore using jsonwebtoken

const loadSocials = async (req, res) => {
const { tokenMail } = req.body;
try {
Expand All @@ -17,4 +19,19 @@ const loadSocials = async (req, res) => {
}
};

module.exports= {loadSocials};
const loadLinks = async (req, res) => {
const { tokenMail } = req.body;
try {
//const decodedTokenMail = jwt_decode(tokenMail, process.env.SECRET_JWT);
const decodedTokenMail = jwt.verify(tokenMail, process.env.SECRET_JWT);
const email = decodedTokenMail.email;
console.log(email);
const user = await User.findOne({ email: email });
const links = user.links;
return res.json({ message: "found", links, status: "success" });
} catch (error) {
return res.json({ status: "error", error: error.message });
}
};

module.exports = { loadSocials, loadLinks };
47 changes: 25 additions & 22 deletions server/controllers/saveItems.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const User = require("../models/user");
const jwt_decode = require("jwt-decode");
const jwt = require("jsonwebtoken");

//jwt-decode does not work anymore usign jsonwebtoken

const saveSocials = async (req, res) => {
const { tokenMail, socials } = req.body;
console.log(req.body);
Expand Down Expand Up @@ -33,32 +35,33 @@ const saveProfile = async (req, res) => {
user.name = name;
user.bio = bio;
user.avatar = avatar;
user.save();
await user.save();
return res.json({ message: "saved", status: "success" });
} catch (err) {
return res.json({ status: "error", error: err.message });
}
};

// const saveLinks = async (req, res) => {
// const { tokenMail, links } = req.body;
// try {
// const decodedTokenMail = jwt_decode(tokenMail, process.env.SECRET_JWT);
// const email = decodedTokenMail.email;
// console.log(email);
// const user = await User.findOne({ email: email });
// console.log(user);
// const newLinks = links.map((link) => ({
// url: link.link.url,
// title: link.link.title,
// icon: ""
// }));
// user.links = newLinks;
// await user.save();
// return res.json({ message: "saved", status: "success" });
// } catch (err) {
// return res.json({ status: "error", error: err.message });
// }
// };
const saveLinks = async (req, res) => {
const { tokenMail, links } = req.body;
try {
//const decodedTokenMail = jwt_decode(tokenMail, process.env.SECRET_JWT);
const decodedTokenMail = jwt.verify(tokenMail, process.env.SECRET_JWT);
const email = decodedTokenMail.email;
console.log(email);
const user = await User.findOne({ email: email });
console.log(user);
const newLinks = links.map((link) => ({
url: link.link.url,
title: link.link.title,
icon: ""
}));
user.links = newLinks;
await user.save();
return res.json({ message: "saved", status: "success" });
} catch (err) {
return res.json({ status: "error", error: err.message });
}
};

module.exports = { saveSocials, saveProfile };
module.exports = { saveSocials, saveProfile, saveLinks };
8 changes: 4 additions & 4 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ const {registerUser, loginUser} = require('./controllers/auth');
require('dotenv').config();
const {dashBoardData} = require('./controllers/dashboard');
const {getUserData, getUserSocials} = require('./controllers/getUserData');
const {saveSocials, saveProfile} = require('./controllers/saveItems');
const {loadSocials} = require('./controllers/loadPrevious');
const {saveSocials, saveProfile, saveLinks} = require('./controllers/saveItems');
const {loadSocials, loadLinks} = require('./controllers/loadPrevious');

app.use(cors());
app.use(express.json());
Expand Down Expand Up @@ -43,9 +43,9 @@ app.get('/get/:handle', getUserData);

app.post("/save/socials", saveSocials);
app.post("/save/profile", saveProfile);
//app.post("/save/links", saveLinks);
app.post("/save/links", saveLinks);
app.post("/load/socials", loadSocials);
//app.post("/load/links", loadLinks);
app.post("/load/links", loadLinks);


const port = process.env.PORT || 8080;
Expand Down
146 changes: 142 additions & 4 deletions site/pages/edit/links.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,147 @@
import React from 'react'
import UserHeader from '../../components/UserHeader';
import React, { useState, useEffect, useContext } from 'react'
import { toast } from 'react-toastify';


const links = () => {
const [links, setLinks]= useState([{url:'', title:''}]);
const [title, setTitle]= useState('');

const handleLinkChange = (index, field, value) => {
const updatedLinks = [...links];
const linkToUpdate = { ...updatedLinks[index], [field]: value };
updatedLinks[index] = linkToUpdate;
setLinks(updatedLinks);
};

const handleAddLink = () => {
setLinks([...links, { url: "", title: "" }]);
};

const handleRemoveLink = (index) => {
const updatedLinks = [...links];
updatedLinks.splice(index, 1);
setLinks(updatedLinks);
};

const saveLinks = (e) => {
e.preventDefault();
const linksArray = Object.values(links);
const titlesArray = Object.values(title);
const linksData = linksArray.map((link, index) => ({
link,
title: titlesArray[index]
}));

fetch(`http://localhost:8080/save/links`, {
method: "POST",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify({
tokenMail: localStorage.getItem("LinkTreeToken"),
links: linksData
})
})
.then((res) => res.json())
.then((data) => {
if (data.status === "error") return toast.error(data.error);
toast.success("Links saved successfully");
})
.catch((err) => {
toast.error(err.message);
});
};

useEffect(() => {
if (!localStorage.getItem("LinkTreeToken")) return router.push("/login");
fetch(`http://localhost:8080/load/links`, {
method: "POST",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify({
tokenMail: localStorage.getItem("LinkTreeToken")
})
})
.then((res) => res.json())
.then((data) => {
if (data.status === "error") return toast.error(data.error);
setLinks(data.links);
});
}, []);

return (
<div>links</div>
)
}
<>
<div>
<UserHeader />
<main>
<section>
<h1 className="text-center font-bold text-xl text-gray-600">
Add or Customize your Links
</h1>
<div>
<form onSubmit={saveLinks}>
{links.map((link, index) => (
<div
className="flex flex-row justify-evenly my-2"
key={index}
>
<label>
URL:
<input
className="outline-none border-2 border-gray-200 shadow-md rounded-md px-2 p-1 ml-2"
type="text"
value={link.url}
onChange={(e) =>
handleLinkChange(index, "url", e.target.value)
}
/>
</label>
<label>
Title:
<input
className="outline-none border-2 border-gray-200 shadow-md rounded-md px-2 p-1 ml-2"
type="text"
value={link.title}
onChange={(e) =>
handleLinkChange(index, "title", e.target.value)
}
/>
</label>
<button
className="bg-indigo-500 text-white px-4 py-2 rounded-md shadow-sm ml-3"
type="button"
onClick={() => {
handleRemoveLink(index);
}}
>
Remove Link
</button>
</div>
))}
<div className="buttons flex flex-row gap-5 my-1">
<button
className="bg-indigo-500 text-white px-4 py-2 rounded-md shadow-sm w-full"
type="button"
onClick={handleAddLink}
>
Add link
</button>
<button
className="bg-green-500 text-white px-4 py-2 rounded-md shadow-sm w-full"
type="submit"
>
Save
</button>
</div>
</form>
</div>
</section>
</main>
</div>
</>
);
};

export default links

0 comments on commit 13c5bca

Please sign in to comment.