Flatiron School Software Development - Phase 2 Recap
Tags: webdev, programming, react, beginners
Published: 2022-07-05 06:09:01

## Again and again. What to write about?
Just like with the previous phases of the course here comes the time when the blog post assignment is due. No surprise there, I struggle with the same dilemma of choosing the topic. The amount of freedom that is given to choose the content does not seem making the decision any easier. I do not want to write a post that is a tutorial. Being a beginner in web development I am not in the position to teach anyone how to code in JavaScript or React. What if my understanding of the concepts is wrong? What if my understanding of the concepts is correct but the solution I have learned is already outdated or there is a better, preferred solution out there. I would rather stay away from writing a tutorial. Then it came to me. What if, instead, I focus on what was covered in the course this phase? It feel like this is exactly what I need. The content being technical should meet the requirements of the blog post assignment. Keeping it personal should make it clear to others that this is not a tutorial and it should not be used to learn anything from it. Finally, writing it in a form of a reference has a purpose of creating a knowledge source I can revisit when I need to write a piece of code I know I learned but the details evaporated from my memory. So here it is. The collection of the most important/good to know/easily forgotten learning points from phase 2 - introduction to React.
To create an empty React app use a template:
`npx create-react-app my-app`
Then resolve all the dependencies:
`npm install`
To add a package to the dependencies, for example [date-fns](https://date-fns.org/):
`npm install date-fns`
To start the app:
`npm start`
A Chrome window should open with the address[](http://localhost:3000). Any time code changes are saved in VS Code, the app should automatically reload.
Destructure props with curly braces:
```javascript
function MovieCard({ title, posterSrc, genres }) {
  return (
    <div className="movie-card">
      <img src={posterSrc} alt={title} />
      <h2>{title}</h2>
      <small>{genres.join(", ")}</small>
    </div>
  );
}
```
Remember to add keys when mapping objects. The keys should have unique values:
```javascript
const userHeadings = users.map((user) => {
  return <h1 key={user.id}>{user.firstName}</h1>;
});
```
Use state when binding components to variables. Remember to give it an initial value:
```javascript
const [count, setCount] = useState(0);
```
Use callback functions, here _onChangeColor_, to send data back to the parent:
```javascript
function Child({ onChangeColor, color }) {
  return (
    <div
      onClick={onChangeColor}
      className="child"
      style={{ backgroundColor: color }}
    />
  );
}
```

Nice generic trick when binding multiple form fields. Remember to keep the names of the ui elements the same as the state object field names.
```javascript
function handleChange(event) {
  // name is the KEY in of the formData object we're trying to update
  const name = event.target.name;
  const value = event.target.value;

  setFormData({
    ...formData,
    [name]: value,
  });
}
```
If you want to fetch data from a server when the component renders for the first time, use `useEffect` with and empty array.
```javascript
useEffect(() => {
  fetch("https://dog.ceo/api/breeds/image/random/3")
    .then((r) => r.json())
    .then((data) => {
      setImages(data.message);
    });
}, []);
```
If you want to fetch data every time the state of `count` variable changes. Update state directly from the response:
```javascript
useEffect(() => {
  fetch("https://dog.ceo/api/breeds/image/random/3")
    .then((r) => r.json())
    .then((data) => {
      setImages(data.message);
    });
}, [count]);
```
Create items:
```javascript
  fetch("http://localhost:4000/items", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(itemData),
  })
    .then((r) => r.json())
    .then((newItem) => console.log(newItem));
}
```
When item is created use spread operator to update state array:
```javascript
function handleAddItem(newItem) {
  setItems([...items, newItem]);
}
```
Use routing when different urls are needed for different components and to access different components by entering  url:
```javascript
<Routes>
        <Route path='/expense' element={<Expense expenseAdded={onExpenseAdded} categories={categories}/>} />
        <Route path='/category' element={<Category categoryAdded={onCategoryAdded}/>}/>
        <Route path='/' element={<Home expenses={expenses}/>}/>
        <Route path='*' element={<div>Not Found!</div>}/>
      </Routes>
```
Use `json-server` for dev environment with db.json file:
`{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}`

`json-server --watch db.json --port 3004`