After fully adding authentication functionality into the Whinst web app I moved on to adding functionality to the home page. I did this by first adding API endpoints(a specific location within an API that accepts requests and sends back responses). The home page has one endpoint which gets the catalogs that a registered user has from the database. In this short article, I'll walk you through how I created and added an API endpoint on the Whinst home page. Let's dive in🚣🏾
Creating the endpoint🔧
To do this I first started with creating a catalog field in the database. I added a few fields which are ID, catalog name and most importantly user ID. The user ID field is the most important because it is a foreign key, it is what is used to link and determine which user created which catalogs.
Creating the actual endpoint was pretty straightforward because I followed the same steps I used when creating the login endpoint. I simply created a get route that when called gets a user ID value sent from the client side via the request parameters and checks for all catalogs in the catalog table that have that particular user ID and sends the result to the client side. The code below is of how this is done.
app.get("/items/:id", async (req, res) => {
try {
const { id } = req.params;
const items = await pool.query("SELECT * FROM items WHERE id = $1",[id])
res.json(items.rows);
} catch (err) {
console.error(err.message);
}
});
Adding the endpoint to the client side⛓
To do this I set up a useEffect function that via the API endpoint uses the ID of the user and requests the catalog information. If the user has catalogs in the database and they are returned, they are stored in state and mapped to be displayed for the user to see their catalogs. The code below is of how this is done.
useEffect(()=>{
async function getData(){
fetch(`http://localhost:5000/items/${id}/`,{
method:'GET',
headers:{
'Content-Type': 'application/json'
},
}).then((response)=>response.json())
.then((json)=>{
setItems(json)
})
}
getData();
},[])
With the homepage done I've since moved on to adding functionality involving API endpoints to all other pages on the web app. Thanks for reading and see you in the next one🙏.