This blog will be a continuation of the last two weeks:

Part I, Part II

The whole point of today’s blog is to break out the ability of the app to add a new candy item to a new file. The App.js file is getting very busy, and, as I add new functions, it will become very difficult to read.

This may seem pedantic when the app can only add new candy. However, it is MUCH easier to come back later and figure out what is going on when functions are broken out into different files and organized.

Here is a picture of what the app looks like at the moment, with the backend and frontend running (github for both in the link for Part II, above).

(need to delete the entries for ‘test candy’)

First thing I want to do is make the app.js file less busy by moving the addCandy function to a separate file. To get started, I create new files for AddNewCandy.js and AddNewCandy.css in the src folder.

AddNewCandy.js will need state, so this will be a class component. I’m going to move all of the new candy return to this file from App.js. I also need to bring over several other files, as well as state for newCandy, the handleChange, :

import React, { Component } from "react"
import "./AddNewCandy.css"

Before going any further, I’m going to change the addCandy function so that it just pulls the candy out of state, and then sends it back up to App.js, all without worrying about the controlled form:

addCandy = candy => {
fetch(`${BASE_URL}/candies`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify( candy )
}).then(response => response.json())
.then(candy => {
this.setState({
candies: [...this.state.candies, candy],
})
})
}

(of course, don’t forget to call it in App.js:

<AddNewCandy addCandy={this.addCandy} />

…as well as update the addCandy function:

addCandy = candy => {
fetch("http://127.0.0.1:3000/candies", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(candy)
}).then(response => response.json())
.then(candy => {
this.setState({
candies: [...this.state.candies, candy],
})
})
}

and finally, move the relevant CSS to the new file created, which associates with the AddNewCandy document:

.add-candy form {
width: 300px;
font-family: Roboto, sans-serif;
}

Done!

It’s not a whole lot for one blog, but practicing moving functions from the app file out into other, utility files is really great practice, and lets you leverage some brilliant React functionality. Next week, I’ll cover and integrate functionality to UPDATE and DELETE candies.

Candy Shop Backend GitHub

Candy Shop Frontend GitHub