<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Reked37</title>
    <description>The latest articles on DEV Community by Reked37 (@reked37).</description>
    <link>https://dev.to/reked37</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1148489%2Faaac76d2-203a-4d88-a87a-22dcf16e5c6b.png</url>
      <title>DEV Community: Reked37</title>
      <link>https://dev.to/reked37</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/reked37"/>
    <language>en</language>
    <item>
      <title>Intro To Redux</title>
      <dc:creator>Reked37</dc:creator>
      <pubDate>Fri, 27 Oct 2023 16:05:02 +0000</pubDate>
      <link>https://dev.to/reked37/intro-to-redux-2le4</link>
      <guid>https://dev.to/reked37/intro-to-redux-2le4</guid>
      <description>&lt;p&gt;Redux is a Javascript library that helps manage the state and passes the correct information to the right component that needs the information. Without Redux, React has to pass the information down to its children's components in order for them to use the data. This can get tedious if the component manipulates data because you must pass down a callback function as a prop. With Redux, you are able to access the state whenever in the program. &lt;/p&gt;

&lt;p&gt;To get started with Redux, there are three key points when setting up Redux. The first point is fairly simple, but that is naming your type of action as a variable so that when the variable is called on, Redux will use that variable to decide on what action will be used. For my project, I built a football website, and this is an example of all my player and fetch request types.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const FETCH_PLAYERS_REQUEST = 'FETCH_PLAYERS_REQUEST'
export const FETCH_PLAYERS_SUCCESS = 'FETCH_PLAYERS_SUCCESS'
export const FETCH_PLAYERS_FAILURE = 'FETCH_PLAYERS_FAILURE'
export const DELETE_PLAYER='DELETE_PLAYER'
export const UPDATE_PLAYER='UPDATE_PLAYER'
export const POST_PLAYER='POST_PLAYER'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next is connecting each type with its specific action. To define an action, you must create a function that returns a Javascript object that accepts type as its first key and value by what type you want it to be connected to. The second key is called payload, which holds the values you are trying to manipulate or pass on. If the program is trying to add a new player to the data, then we would use POST_PLAYER type inside the post-player function we create and put the newPlayer as the payload. The code would look something like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const postPlayer=(newPlayer)=&amp;gt;{
    return{
        type:POST_PLAYER,
        payload:newPlayer
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lastly, the most complicated out of the three parts is the reducer. The reducer starts with an initial state variable, which is a javascript object that has three keys: response, data, and errors. The initial state would look like this, where the data key is replaced by the name of the data you are going to set it to. Since I'm fetching the players of the football league, I set the key to be leaguePlayers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const initialState={
    loading: false,
    leaguePlayers: [],
    error:''
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next is defining the function of the reducer, which checks the type of the action and tries to find the type that matches its correct condition using a switch statement. The function will take two arguments: the state and the action. When the reducer is initialized, it will look through the switch statement until it comes across the correct type. After the condition has been found, we then perform the correct actions on the data type. Below is what my reducer looks like for my player data as I have it set up to fetch the data from an API, along with delete, post, and update.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const playerReducer =(state=initialState, action)=&amp;gt;{
    switch(action.type){
        case FETCH_PLAYERS_REQUEST: return{
            ...state,
            loading: true
        }
        case FETCH_PLAYERS_SUCCESS: return{
            loading: false,
            leaguePlayers: action.payload,
            error: ''
        } 
        case FETCH_PLAYERS_FAILURE: return{
            loading: false,
            leaguePlayers: [],
            error: action.payload
        }
        case DELETE_PLAYER:return{
            ...state,
            leaguePlayers: state.leaguePlayers.filter((player)=&amp;gt;{
                return player.id !==action.payload
            })
        }
        case UPDATE_PLAYER:return{
            ...state,
            leaguePlayers: state.leaguePlayers.map(player=&amp;gt;{
                if(player.id === action.payload.id){
                    return action.payload
                }
            return player}),
            error:''
        }
        case POST_PLAYER: return{
            ...state,
            leaguePlayer: [...state.leaguePlayers, action.payload]
        }
        default: return state
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the spread operator lets us copy the original state and manipulate the data. So, for the post-player method, we have the key leaguePlayer and defined its new values as an array with all the players' data along with the new player and appended at the end.&lt;br&gt;
Those are the three key points of Redux; now we have to implement it into the project. We'll start off by creating a file called 'Store' and import the following from redux along with redux-thunk: createStore, combineReducers, applyMiddleware. The combineReducer allows the program to use multiple reducers by setting combineReducers to a variable, usually called rootReducer, and setting each reducer to its own key and value pair.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const rootReducer=combineReducers({
    players: playerReducer,
    teams: teamReducer,
    coaches:coachReducer,
    matches: matchReducer
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By setting createStore to a variable, we are able to pass in the rootReducer and applyMiddleware where we will pass in 'thunk' to applyMiddleware. The statement will look like this, where 'store' is how we will access the state in the program.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const store =createStore(rootReducer, applyMiddleware(thunk))
export default store
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inside the program, we will want to import 'Provider' from react-redux, where the Provider component will be wrapped around the entire program of the App file and pass store={store} as a prop so every component will be able to use the state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {

  return(
    &amp;lt;Provider store={store}&amp;gt;
    &amp;lt;div class='background'&amp;gt;
      &amp;lt;NavBar /&amp;gt;
      &amp;lt;Routes&amp;gt;
        &amp;lt;Route path="/" element={&amp;lt;Home /&amp;gt;}&amp;gt;&amp;lt;/Route&amp;gt;
        &amp;lt;Route path="/players" element={&amp;lt;PlayersContainer /&amp;gt;}&amp;gt;&amp;lt;/Route&amp;gt;
        &amp;lt;Route path="/coaches" element={&amp;lt;CoachesContainer /&amp;gt;}&amp;gt;&amp;lt;/Route&amp;gt;
        &amp;lt;Route path="/teams" element={&amp;lt;TeamsContainer /&amp;gt;}&amp;gt;&amp;lt;/Route&amp;gt;
        &amp;lt;Route path='/matches' element={&amp;lt;MatchesContainer /&amp;gt;}&amp;gt;&amp;lt;/Route&amp;gt;
        &amp;lt;Route path="/add" element={&amp;lt;Add /&amp;gt;}&amp;gt;&amp;lt;/Route&amp;gt;
        &amp;lt;Route path='/players/:id' element={&amp;lt;UpdatePlayer /&amp;gt;}&amp;gt;&amp;lt;/Route&amp;gt;
        &amp;lt;Route path='/playerscoaches/:id' element={&amp;lt;ShowPlayersCoaches /&amp;gt;}/&amp;gt;
        &amp;lt;Route path='/coachesplayers/:id' element={&amp;lt;ShowCoachesPlayers /&amp;gt;}/&amp;gt;
        &amp;lt;Route path='/teamcoaches/:id' element={&amp;lt;ShowTeamCoaches /&amp;gt;}/&amp;gt; 
        &amp;lt;Route path='/teamplayers/:id' element={&amp;lt;ShowTeamPlayers /&amp;gt;}/&amp;gt;
        &amp;lt;Route path='/coaches/:id' element={&amp;lt;UpdateCoach/&amp;gt;}/&amp;gt;
      &amp;lt;/Routes&amp;gt; 
    &amp;lt;/div&amp;gt;
    &amp;lt;/Provider&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once we have a component that needs access to the state, we will need to import useSelector, how we select the state we want to use and useDispatch to manipulate the data from the actions we previously defined. Using the useSelector is fairly simple, as it only takes one line of code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const players = useSelector(state=&amp;gt;state.players.leaguePlayers)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The useDispatch is how we will update the old state and return the new state. By passing in the function of our actions to useDispatch we are able to manipulate the data correctly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const dispatch=useDispatch()
dispatch(deletePlayer(passPlayer.id))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To conclude, there are many aspects of Redux, but once you get the hang of it, it can make the life of a programmer ten times easier. You won't need to pass down data to each child component, but instead, Redux will manage and keep the state updated for the other components, so you don't have to.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>redux</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>RESTful API</title>
      <dc:creator>Reked37</dc:creator>
      <pubDate>Mon, 02 Oct 2023 17:29:23 +0000</pubDate>
      <link>https://dev.to/reked37/restful-api-30ce</link>
      <guid>https://dev.to/reked37/restful-api-30ce</guid>
      <description>&lt;p&gt;One of the amazing tools that was introduced to the tech world was the structure of RESTful API. Before that, developers used SOAP, which was a set of rules that had to be followed when creating a web service. The switch over to REST made the life of a developer easier as it was an architectural style on how to structure code. One of the key differences was using a decorator to define a route and then give it the correct methods that it would use; compared to RESTful which defined each of its route handling methods as a class method.&lt;br&gt;
Before:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route('/campers', methods=['GET', 'POST'])
def campers():
    if request.method == 'GET':
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Campers(Resource):
    def get(self):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This saved time for developers as they didn't have to define each method but instead would look for the proper fetch request to handle what the website was trying to do. Another key difference is where the route is being defined as the old way defined the path with the methods, REST uses add_resource(), on the API, which takes in two arguments. The first one is the class name, and the other describes the route.&lt;br&gt;
&lt;code&gt;api.add_resource(Campers, '/campers' )&lt;/code&gt;&lt;br&gt;
After defining the routes and the methods, the next step is to define the fetches within our class. The class takes in 'Resource' from Flask-RESTful which is a framework when building out the fetches. For the first fetch method, we will define 'get' and pass in the argument 'self.' When the website sends a get request to our backend, the class will look for the class method that matches the request. For this blog, I'll focus on CRUD (create, read, update, delete) and use the get, post, patch, and delete methods. &lt;br&gt;
For the get method, we must first retrieve all the data from the data table we are trying to display and convert each entry into its own dictionary using the to_dict() method, which we easily accomplish with a list comprehension. After getting the information, the client needs a response from the backend so we'll have to use make_response() which takes in two arguments: a JSONify object and a response code that was successful in retrieving the information. Then all we need to do is return the response so the client can use the information.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Campers(Resource):
    def get(self):
        campers=Camper.query.all()
        campers_dict=[camper.to_dict() for camper in campers]
        response=make_response(
            jsonify(campers_dict),
            200
        )
        return response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The post method differs from the get request as it has to retrieve data from a form that was submitted by the front end. To be able to retrieve that data, we'll use 'request.get_json()' and then look for the particular value from the key. Then we will have to add this new entry to our database and convert the new entry into a dictionary. We will use the same make_respose() method then justify our dictionary and return a response code of 201 for a newly created entry.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def post(self):
        json=request.get_json()
        new_camper=Camper(
            name=json['name'],
            equipment=json['equipment'],
        )
        db.session.add(new_camper)
        db.session.commit()
        camper_dict=new_camper.to_dict()
        response=make_response(jsonify(camper_dict), 201)
        return response
api.add_resource(Campers, '/campers')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The delete fetch will be the easiest method to create but will have to take in a parameter of the entry's ID to specify which entry to delete. This requires a new view that is able to pass in the ID we need from the URL path. With the ID, we will query our search using the ID and then delete it from the data table. For the response, we won't be giving the client any information from our data tables, but we will still want to give the client that the data entry has been deleted. Defining a variable called response_body and creating a dictionary saying the data entry has been deleted will suffice for our make_response and then return the response. Notice at the end the route has &lt;a&gt;int:id&lt;/a&gt; to specify where the fetch will be getting the id from.&lt;br&gt;
&lt;code&gt;api.add_resource(CamperByID, '/campers/&amp;lt;int:id&amp;gt;')&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def delete(self, id):
        player=Player.query.filter_by(id=id).first()
        db.session.delete(player)
        db.session.commit()
        response_body={"message": "Player has been successfully deleted"}
        response=make_response(
            response_body,
            200
        )
        return response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lastly, we have the patch fetch which uses a little bit from each method. The patch will use the same view as the delete fetch because the backend needs to specify which data entry we need to update. First, we'll query for the particular data entry as we did for the delete method. Secondly, we need to retrieve the data from the form that will update the given information from the request.get_json(). Next, we'll have to create a loop to update each attribute in the data entry with the new data but will keep the old data if none of the old data changes. Then add the updated entry to the database. Lastly, we will convert the data entry to a dictionary using the to_dict() method. Create the response for the client's end, and that's the patch method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    def patch(self,id):
        camper=Camper.query.filter_by(id=id).first()
        json=request.get_json()
        for attr in json:
            setattr(camper, attr, json[attr])

        db.session.add(camper)
        db.session.commit()
        camper_dict=camper.to_dict()
        response=make_response(jsonify(camper_dict), 200)
        return response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To conclude, Flask-Restful makes a developer's job a whole lot easier when it comes to structuring the fetches inside a view and skips out on a lot of repetitive code and defining which methods will be used in each view. &lt;/p&gt;

</description>
      <category>python</category>
      <category>api</category>
      <category>github</category>
      <category>learning</category>
    </item>
    <item>
      <title>Starting My First Command Line Project</title>
      <dc:creator>Reked37</dc:creator>
      <pubDate>Mon, 28 Aug 2023 21:21:30 +0000</pubDate>
      <link>https://dev.to/reked37/starting-my-first-command-line-project-ki3</link>
      <guid>https://dev.to/reked37/starting-my-first-command-line-project-ki3</guid>
      <description>&lt;p&gt;Starting out, I had a few ideas on what to create my project about, one being a weekly planner that you could fill in daily what you wanted to accomplish or plan to do. So, if you ever have problems remembering what you are supposed to do on a particular day, you could look to the CLI Weekly Planner. I also mauled over the idea of creating a little interactive game depending on the chosen path but stirred away from the idea because I couldn't determine what to make the game about. Lastly, I stumbled over a Password Manager project that would store your login information to a particular website. This seemed more straightforward, so that's what I went with. Sweet, moving on!&lt;/p&gt;

&lt;p&gt;Setting up the environment to start my project was relatively easy. A file was provided for me that I had to connect to my Git Hub so I could use all the fancy features of git add, git commit, and git push. Next, I had to create some data tables to store all the login details for the user which I used sqlalchemy and alembic to get that started.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pipenv install sqlalchemy alembic
alembic init migrations
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After installing that, I had to configure the alembic to generate my database properly. In the eny.py file in migrations, I updated the target_metadata to equal Base.metadata from models and renamed my database in the alembic.ini file. Lastly, I ran &lt;br&gt;
&lt;code&gt;alembic revision --autogenerate -m'intialize'&lt;/code&gt;&lt;br&gt;
to get my database generated and setup my project.&lt;/p&gt;

&lt;p&gt;I found two main parts of my project the most difficult: setting up the schema for my database and creating the proper functionality for my command line to interact with my database.&lt;/p&gt;

&lt;p&gt;For my models.py, I created two tables named User and Website that contained the user's login information and a data table that stored all the websites that would be validated when entering a new login entry. The Website model is used to check whether the site exists before entering the data into the user's login info for that website. The user can add more websites to the data table through the command line application. &lt;br&gt;
`&lt;br&gt;
class User(Base):&lt;br&gt;
    &lt;strong&gt;tablename&lt;/strong&gt; = 'users'&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;id= Column(Integer(), primary_key=True)
website_name= Column(String())
username= Column(String())
password= Column(String())
website_id= Column(Integer(), ForeignKey('websites.id'))
browser_id= Column(Integer(), ForeignKey('browsers.id'))

def __repr__(self):
    return f'User(id={self.id},' + \
    f'website_name={self.website_name},' + \
    f'username={self.username},' + \
    f'password={self.password})'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;class Website(Base):&lt;br&gt;
    &lt;strong&gt;tablename&lt;/strong&gt;= 'websites'&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;id= Column(Integer(), primary_key=True)
website= Column(String())
created= Column(DateTime())

users= relationship('User', backref=backref('website'))

def __repr__(self):
    return f'Website(id={self.id},' + \
    f'website={self.website},' + \
    f'created={self.created})'`
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;I was establishing a one-to-many relationship between the user and the website so that when a login entry was entered, there would be a corresponding website.id on the user table to show what login was "owned" by which website. Using the relationship from SQLalchemy helps to establish this relationship with the help of backref's and ForeignKey. In the above code, I defined a variable 'users' to equal relationship and assigned the 'User' class to the first argument of the relationship and a backref or back reference to be 'website' so that the one-to-many relationship would look back at the website table to fill in the necessary data for the user. Next, in the User class, I defined website_id to equal its column on the table and fill in that data from websites. I chose to use websites.id instead of websites.website_name to fill in the data, but either option works to set up the one-to-many relationship.&lt;/p&gt;

&lt;p&gt;For creating a new entry to be added to the data table, I made the functionality in its file called create.py that would take the user's inputs and store them, and set up the session that would interact with the database. This is done in the function called 'add_to_database().'&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def create_new_entry(session, website_name, username, password, entered_browser):
    valid_website=session.query(Website).filter_by(website=website_name).first()
    valid_browser= session.query(Browser).filter_by(browser_name=entered_browser).first()

if not valid_website:
        print(f'{website_name} is not a valid website')

    if not valid_browser:
        print(f'{entered_browser} is not a valid browser')

    #dictionary
    new_entry={'website_name': website_name, 'username': username, 'password': password, 'website_id':valid_website.id, 'browser_id': valid_browser.id}
    session.add(User(**new_entry))
    session.commit()
    return new_entry

def add_to_database():
    engine=create_engine('sqlite:///projectdatabase.db')
    Session= sessionmaker(bind=engine)
    session= Session()

    entered_browser=input('What browser do you prefer? ')
    website_name=input('Name of website: ')
    username=input('Username: ')
    password=input('Password: ')

    entry=create_new_entry(session, website_name, username, password, entered_browser)

    print("New entry created!")

    session.close()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After the session is created and the input stored, I pass the data to the function that will make the new entry called 'create_new_entry.' The first snippet of code is a query session that looks to see if the website_name given by the user is in the database. If the website isn't in the database, then the program responds back that the website isn't valid and will exit out of the command line. However, if the website is already in the database, everything gets bundled into a dictionary. Then, the function calls upon the User class and creates an instance with the dictionary given, and using the unpack method allows for a new entry to be created and added to the data table. After the entry is added, the command line will respond with "New entry created!" from add_to_database and close the session.&lt;/p&gt;

&lt;p&gt;To conclude, setting up the models with the right tools and knowing how to use the tools the right way played a big part in setting a one-to-many relationship with the relationship and backref belonging to the owner or what's being referenced. The ForeignKey allows for that table to look back at which table it needs to get the data off of to fill in that portion of the table. Lastly, finding the right data point from a data base using session.query to see if specific data existed before creating the entry as the filter_by method takes in where to look, that being 'website' and what to compare that data to. It then created a new entry with the User class and appended it to the table with session.&lt;/p&gt;

</description>
      <category>sql</category>
      <category>cli</category>
    </item>
  </channel>
</rss>
