This project was bootstrapped with Create React App. (Read more about this app in the auto-generated README-react-app.md document.)
Node.js is required for local development.
To view the entire completed project for development locally, you'll need to open two terminal windows for your Node.js environment. Run the following in your project root:
npx json-server --watch data/db.json --port 8000
npm run start
After running the second command, your browser should automatically open the application, e.g. http://localhost:3000/
.
Open up a third, separate terminal for any development purposes; keep the first two Node instances running in the background while you work.
- Install
node.js
if necessary. - Navigate to the directory where you want to create your project root.
- Run the Create React App, replacing "project-name" with your own project:
npx create-react-app project-name
For simple projects, you can delete the following:
- src/App.test.js
- src/reportWebVitals.js
- Open src/index.js to delete
import reportWebVitals from './reportWebVitals';
andreportWebVitals();
.
- Open src/index.js to delete
- src/setupTests.js
In your terminal, run npm run start
to execute the script which starts React and allows you to view your project in the browser.
At Step 16, this project starts using dummy content to simulate fetching blog posts from a database:
-
Create a directory & JSON file with the blog content: data/db.json
-
In the root project directory, run:
npx json-server --watch data/db.json --port 8000
This starts a server which points to your database which you can query as a url/endpoint within your code. Changing the port is necessary because the server will default to port 3000, which is already in use by React.
Note: you may need to re-run npm run start
after starting the json server.
-
- GET - Fetch all blogs
- POST - Add a new blog
-
- GET - Fetch a single blog
- DELETE - Delete a blog
Step 19 is all about error handling for network problems or URL/endpoint (resource) issues.
- Disconnect from json-server:
ctrl+C
- Refresh the page in your browser. Any connection errors will be captured by the catch block and can be logged to the console.
- Reconnect to json-server after testing:
npx json-server --watch data/db.json --port 8000
- In the fetch block, change the URL to something nonexistent, e.g.
"http://localhost:8000/blogs%%%%%"
. - Refresh the page in your browser. Anything other than a successful delivery of the desired resource from the server will throw an Error("message") to the catch block.
- Reset the URL after testing, e.g.
http://localhost:8000/blogs
Step 21 requires installation of a new dependency, the React Router. In a new terminal, run npm install react-router-dom@5
. Once installed, view the package.json file to see the "react-router-dom..." listed under dependencies.