DEV Community

Mariusz Bialobrzeski
Mariusz Bialobrzeski

Posted on

Flatiron School Software Development - Phase 2 Recap

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:
npm install date-fns
To start the app:
npm start
A Chrome window should open with the address. Any time code changes are saved in VS Code, the app should automatically reload.
Destructure props with curly braces:

function MovieCard({ title, posterSrc, genres }) {
  return (
    <div className="movie-card">
      <img src={posterSrc} alt={title} />
      <h2>{title}</h2>
      <small>{genres.join(", ")}</small>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Remember to add keys when mapping objects. The keys should have unique values:

const userHeadings = users.map((user) => {
  return <h1 key={user.id}>{user.firstName}</h1>;
});
Enter fullscreen mode Exit fullscreen mode

Use state when binding components to variables. Remember to give it an initial value:

const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

Use callback functions, here onChangeColor, to send data back to the parent:

function Child({ onChangeColor, color }) {
  return (
    <div
      onClick={onChangeColor}
      className="child"
      style={{ backgroundColor: color }}
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

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.

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,
  });
}
Enter fullscreen mode Exit fullscreen mode

If you want to fetch data from a server when the component renders for the first time, use useEffect with and empty array.

useEffect(() => {
  fetch("https://dog.ceo/api/breeds/image/random/3")
    .then((r) => r.json())
    .then((data) => {
      setImages(data.message);
    });
}, []);
Enter fullscreen mode Exit fullscreen mode

If you want to fetch data every time the state of count variable changes. Update state directly from the response:

useEffect(() => {
  fetch("https://dog.ceo/api/breeds/image/random/3")
    .then((r) => r.json())
    .then((data) => {
      setImages(data.message);
    });
}, [count]);
Enter fullscreen mode Exit fullscreen mode

Create items:

  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));
}
Enter fullscreen mode Exit fullscreen mode

When item is created use spread operator to update state array:

function handleAddItem(newItem) {
  setItems([...items, newItem]);
}
Enter fullscreen mode Exit fullscreen mode

Use routing when different urls are needed for different components and to access different components by entering url:

<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>
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)