Creating Data with the Front End
Creating Data with the Frontend
Creating Lunch Week Data#
In this lesson, we are going to create new lunchWeek
entities using the backend POST /lunch-week
endpoint. Here's the plan for enabling this feature in the front end:
Add a New Lunch Week button to the
LunchMenuAdmin
componentThe button will open a Create Lunch Week modal that will contain a date input for the
weekOf
dateOnce the user confirms the Create Lunch Week modal, the front end will call the POST lunch week endpoint
The endpoint will return a payload with the new
lunchWeekId
. We'll use that response payload to add a row to thelunch_week
table.
Let's get started by adding some state variables and functions to the script section in LunchMenuAdmin.svelte
.
We need a variable called showCreateModal
and one called createWeekOfDate
, and we will need openCreateModal
and createLunchWeek
functions:
let showCreateModal = false
let createWeekOfDate = null
const openCreateModal = () => {
showCreateModal = true
}
const createLunchWeek = async () => {
showCreateModal = false
let newLunchWeek = {
weekOf: createWeekOfDate, // createWeekOfDate will contain the input from the user
isPublished: false,
}
try {
loading = true
// since this is a POST, we need to send a lunchWeek object as the body of the request
const response = await axios.post(`${process.env.API_ROOT}/api/lunch-week`, newLunchWeek)
const lunchWeekId = response.data.lunchWeekId
// populate the newLunchWeek with the id from the server response
newLunchWeek.lunchWeekId = lunchWeekId
// push the result into lunchWeek list, so that
// Svelte will update the table
lunchWeekList.push(newLunchWeek)
loading = false
} catch (e) {
loading = false
console.error(e)
}
}
Then in the markup, add the <button>
to open the modal above the table:
This page is a preview of Fullstack Svelte