Node, Express, Sequelize, PostgreSQL, and React App Part 2 — Seeding and Starting the React Frontend
Part 1 of this series focused on setting up the backend with Node, Express, Sequelize, and PostgeSQL. Part 2 will will focus on what I learned while seeding the tables and setting up the skeleton for the React frontend.
It’s getting seedy…
The Sequelize commands for setting up the seed files:
sequelize seed:create --name my-seed-file
Ideas Seed
'use strict';module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert('Ideas', [{
subject : 'First song',
category : 'Music',
createdAt : new Date(),
updatedAt : new Date()
}], {});
},down: (queryInterface, Sequelize) => {
queryInterface.bulkDelete('Ideas', [{
subject :'First song'
}])
}
};
Contents Seed
'use strict';module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert('Contents', [{
idea_id : 1,
post : 'Great lyrics',
audio : 'sounds',
createdAt : new Date(),
updatedAt : new Date()
}], {});
},down: (queryInterface, Sequelize) => {
queryInterface.bulkDelete('Contents', [{
post :'Great lyrics'
}])
}
};
Run the seed command like this:
sequelize db:seed:all
You can check the tables to see if it seeded correctly like so:
psql ideaSELECT * FROM "Ideas";
SELECT * FROM "Contents";
React
I assume that most of the people reading this blog post are already familiar with how to code in React, so I will discuss my approach for creating this IdeaPad app and highlight interesting things that I learned along the way.
What we have so far is the basic skeleton of this app that posts Ideas and Contents for each Idea. An Idea can be posted with the IdeaForm. Each Idea consists of a subject and a category (not currently displayed, but will be there in the future along with a filter by category feature). When an Idea is clicked, it will display the Contents under that idea. Each Content consists of a post textarea field and an audio input field (currently just a string, but will be an audio file that can be uploaded or recorded). There is also a ContentForm that lets you post more Contents to each idea.
One of the interesting errors that I got while fetching Ideas from the backend was the No CORS Error. The fix for this was quite simple:
postIdea = (idea) => {
fetch(`/api/idea/`, {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json; charset=utf-8",
},
redirect: "follow",
referrer: "no-referrer",
body: JSON.stringify(idea)
})
.then(r => r.json())
.then(r => {
this.fetchIdeas()
})
}
You can see that when you are fetching from a Node/Express backend, you don’t need to include localhost:3000 or whatever port you are using when you fetch.
See you in the next installment!
Sources
https://gist.github.com/vapurrmaid/a111bf3fc0224751cb2f76532aac2465