rajlanjewar01/react-books
React app with context API
App Phases:
-
Local, non-persisted list of books (#1)
-
List of books persisted with outside API (rajlanjewar01/react-books#2)
-
Outside API + centralized store (rajlanjewar01/react-books#4)
-
useCallback (rajlanjewar01/react-books#7)
-
Notable changes:
Deploying json-server to hosting platform with Render.com [https://github.com/rajlanjewar01/react-books/pull/5]
Linked project:
https://github.com/rajlanjewar01/json-server
List of books persisted with outside API
Things we need to do:
- Create the API and undertand how it works.
- When app start ups, make a request to API to get the current list of books.
- When user Create/Edit/Delete a book, update the API and then update the local data.
JSON server setup:
- Install JSON-server with NPM at the terminal
- Create db.json file. This is where data will be stored
- Create a command to run a JSON-Server
- Run the command
Run the application:
Two commands to start project -
npm run server- Starts JSON-Servernpm run start- Start the React Dev server
*1. How API works: *
| Goal | URL | Method | Request Body | Response Body |
|---|---|---|---|---|
| Create Book | localhost:3001/books | POST | {"title": "Harry Potter"} |
{"id": 1, "title": "Harry Potter"} |
| Get All Books | localhost:3001/books | GET | - | [{"id": 1, "title": "Harry Potter"}] |
| Update Book | localhost:3001/books/1 | PUT | {"id": 1, "title": "Rich Dad, Poor Dad"} |
{"id": 1, "title": "Rich Dad, Poor Dad"} |
| Delete Book | localhost:3001/books/1 | DELETE | - | {"id": 1, "title": "Harry Potter"} |
-
Create/Edit/Delete a book, update the API and then update the local data
install
axiosApp.js
import axios from 'axios';
const createBook = async(title) => {
const response = await axios.post('http://localhost:3001/books', {
title
});
const updatedBooks = [
...books,
response.data
];
setBooks(updatedBooks);
}- On App startup make a request to API to get the current list of books
useEffect
- Function that we import from React
- Used to run code when a component is initailly rendered and (sometimes) when it is rerendered
useEffect(() => {
console.log('Hi!');
}, [])-
First argument is a function that contains code we want to run
-
Second argument is an array or nothing - this contains whether the function is executed on rerenders
-
Variations of
useEffect
Video notes: https://xxx.udemy.com/course/react-redux/learn/lecture/34694682#content
Practice code: https://www.codepen.io/sgrider/pen/BarEowz
- With argument
useEffect(() => {
console.log('Hi!');
}, [])
i) Second argument is []
ii) Called after first render
iii) Never called again
- No argument
useEffect(() => {
console.log('Hi!');
})
i) Second argument is -
ii) Called after first render
iii) Also called after every rerender
- With argument and value
useEffect(() => {
console.log('Hi!');
}, [counter])
i) Second argument is [ counter]
ii) called after first render
iii) Also called after rerenders if 'counter' variable changed