Skip to main content

MERN Simple Update

We can alter the way our app looks (change CSS) based on our data.

We'll gray out our holidays based on whether or not we have celebrated them (a boolean, defaulted to false)

Let's write a toggle function

const toggleCelebrated = async (holiday) => {
const response = await fetch(`/api/holidays/${id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ ...holiday, celebrated: !holiday.celebrated }),
});
const jsonData = await response.json();
setHolidays(
holidays.map((holiday) => {
if (holiday.id === jsonData.id) {
return jsonData;
}
return holiday;
})
);
};

Add an event listener to the holiday name and toggle the css of the name. Again because we need to pass an argument we have to wrap our function in an anonymous function for our event handler

<td
onDoubleClick={() => toggleCelebrated(holiday)}
className={holiday.celebrated ? "celebrated" : null}
>
{holiday.name} Day
</td>

Your turn

Everyone

Create the functionality to increase the number of likes by clicking an image of balloons

Increase Likes

Add two new tds

  • one that has the total number of likes
  • one that has an emoji of a balloon
<td>{holiday.likes}</td>
<td>
<button>🎈</button>
</td>

Bonus

Modal Update

Create the functionality to update all the fields with a form that pops up as a modal or opens on a new route:

  • make sure that the form is pre-populated with values
<td>
<button>🖊</button>
</td>

Airtable

In order to try this out for project 2, you cannot use JSON server, but have to use something like Airtable instead

Do the following:

  • Sign-up
  • Setup a base using the same structure as holidays
  • Get a token
  • Goto their API

You will need to adapt your fetch to the Airtable API for example:

App.jsx
const TOKEN = "my_secret_token";
const BASE_URL = "https://api.airtable.com/v0/apppRarCsPf4hzlWc/holidays"

useEffect(() => {
async function fetchHolidays() {
const response = await fetch(`${BASE_URL}/holidays`, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${TOKEN}`,
},
});
const jsonData = await response.json();
const holidaysData = jsonData.records.map((data) => ({
...data.fields,
id: data.id,
}));
setHolidays(holidaysData);
}
fetchHolidays();
}, []);