<?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: Tobi Ojuolape</title>
    <description>The latest articles on DEV Community by Tobi Ojuolape (@tobiojuolape).</description>
    <link>https://dev.to/tobiojuolape</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%2F912029%2Fbe35a248-efba-493e-a34a-0d1e50f69445.jpeg</url>
      <title>DEV Community: Tobi Ojuolape</title>
      <link>https://dev.to/tobiojuolape</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/tobiojuolape"/>
    <language>en</language>
    <item>
      <title>A simple guide to Javascript event handling in React</title>
      <dc:creator>Tobi Ojuolape</dc:creator>
      <pubDate>Sun, 06 Nov 2022 16:53:04 +0000</pubDate>
      <link>https://dev.to/tobiojuolape/a-simple-guide-to-javascript-event-handling-in-react-417h</link>
      <guid>https://dev.to/tobiojuolape/a-simple-guide-to-javascript-event-handling-in-react-417h</guid>
      <description>&lt;p&gt;The main purpose of Javascript in web development is to handle interactions between the user and the web interface - what happens when a user fills a form or clicks a button? These interactions are usually handled through something called “Events” in Javascript, hence handling these events in the best way possible would lead to better interaction and optimize user experience. &lt;/p&gt;

&lt;p&gt;An event handler is a simple form of Javascript code that is usually added to an HTML or JSX element to handle the interaction between the user and the frontend interface.  Javascript has several event handlers which can be used for different purposes. &lt;/p&gt;

&lt;p&gt;In this article, I would be highlighting some of the most important event handlers in Javascript and when to use them.&lt;/p&gt;

&lt;h2&gt;
  
  
  1) OnClick
&lt;/h2&gt;

&lt;p&gt;This event handler controls interactions that occur when a user clicks an element on the interface. It is worth noting that although buttons are the most preferred elements to use with this event handler, any HTML element can have an onClick event handler. &lt;/p&gt;

&lt;p&gt;An example implementation of the onClick event handler can be found below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div className="flex justify-center my-4"&amp;gt;
          &amp;lt;img
            className="cursor-pointer"
            onClick={() =&amp;gt; window.location.open('/')}
            src={Logo}
            alt="logo"
          /&amp;gt;
        &amp;lt;/div&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the Javascript React code above, the onClick event handler is added to a logo image and redirects the user to the homepage of the app when clicked.&lt;/p&gt;

&lt;h2&gt;
  
  
  2) OnSubmit
&lt;/h2&gt;

&lt;p&gt;This event handler controls form submissions, particularly when the enter button is pressed on a form element. To prevent the default behaviour of form submission which usually reloads the page, it is best to attach the onSubmit event handler as an onSubmit.prevent instead, or yet insert a prevent default function to disable the default behaviour of a submit event handler.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      &amp;lt;form onSubmit={(e)=&amp;gt;handleSubmit(e)}&amp;gt;
            &amp;lt;label&amp;gt;Name&amp;lt;/label&amp;gt;
            &amp;lt;input onChange={(e)=&amp;gt;setName(e.target.value)}&amp;gt;&amp;lt;/input&amp;gt;
        &amp;lt;/form&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3) OnChange
&lt;/h2&gt;

&lt;p&gt;This event handler is typically used to detect changes made to an HTML input element and fire a function to update a data value based on this change. The target.value property of the event that fires usually contains the data needed. An example implementation of the onChange event handler can be found below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react"

const [name,setName] = React.useState("")
function nameForm(){
return(
&amp;lt;label&amp;gt;Name&amp;lt;/label&amp;gt;
&amp;lt;input type="text" onChange={(e)=&amp;gt;setName(e.target.value)}&amp;gt;&amp;lt;/input&amp;gt;
)
}

export default nameForm

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this react component, the onChange event handler is being used to set the value of the Name data upon every input. &lt;/p&gt;

&lt;h2&gt;
  
  
  4) OnKeyDown and OnKeyUp
&lt;/h2&gt;

&lt;p&gt;These event handlers control when a key on the keyboard has been pressed. Its use is quite similar to the onChange event handler, however, the major difference is that both OnKeyDown and OnKeyUp also return the key that was pressed. Although OnKeyDown and OnKeyUp perform similar functions, a differentiator between the two is that OnkeyDown is fired when a button on the keyboard is pressed while OnKeyUp is fired when a button on the keyboard is released. As a result, the OnKeyDown event handler is faster and more commonly used than the OnKeyUp event handler. &lt;/p&gt;

&lt;p&gt;An example implementation of OnKeyDown and OnKeyUp event handlers is displayed below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react'

const [name,setName] = React.useState("")

function dobForm(){
return(
&amp;lt;form onSubmit={(e)=&amp;gt;handleSubmit(e)}&amp;gt;
            &amp;lt;label&amp;gt;Date of birth&amp;lt;/label&amp;gt;
            &amp;lt;input type="date"           
      onKeyDown={(e)=&amp;gt;setName(e.target.value)}&amp;gt;&amp;lt;/input&amp;gt;
        &amp;lt;/form&amp;gt;
)}

export default dobForm
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;As Javascript provides a lot of options of handling events, it can get quite confusing to know which event handlers to use for a particular case. The general rule of thumb to follow in cases like this would be:&lt;/p&gt;

&lt;p&gt;If your interaction is a "clicky" one, use the onclick event handler&lt;/p&gt;

&lt;p&gt;If your interaction is an input form one, use the onSubmit event handler to handle it&lt;/p&gt;

&lt;p&gt;If you would like to get data from a textfield/select field input, use the onChange event handler&lt;/p&gt;

&lt;p&gt;You can also read up on more event handlers in Javascript by clicking &lt;a href="https://www.w3schools.com/tags/ref_eventattributes.asp"&gt;here&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>react</category>
      <category>programming</category>
    </item>
    <item>
      <title>A simple guide to consuming APIs with Redux (tutorial example)</title>
      <dc:creator>Tobi Ojuolape</dc:creator>
      <pubDate>Mon, 26 Sep 2022 09:25:26 +0000</pubDate>
      <link>https://dev.to/tobiojuolape/a-simple-guide-to-consuming-apis-in-redux-with-example-438</link>
      <guid>https://dev.to/tobiojuolape/a-simple-guide-to-consuming-apis-in-redux-with-example-438</guid>
      <description>&lt;p&gt;One of the advantages of Javascript frameworks that use flux pattern is the ease with which data can be passed from a parent component to a child component and vice versa. However, there are situations where the same data needs to be used by more than one parent component in a React app. &lt;/p&gt;

&lt;p&gt;For instance, a React app that makes a get request to an endpoint to fetch data from a server – If the data received as a response is to be used by more than one page of the React app, how do we make this work? &lt;strong&gt;State management&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;With state management, we can create a store that will serve as the “single source of truth” for all the data being used by multiple pages in our react app. Without state management, the developer would need to make independent API calls in each component that requires the data from the API and this approach is not ideal as it might result in:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Slow response time as each page would need to re-fetch the data for each page visit&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Overloading of servers as they would be fulfilling multiple requests at the same time. &lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In this article, we’ll be building a react app that uses Redux to fetch user data from the Randomuser API, save the data in the store and makes it available to all components and pages within the react app.&lt;/p&gt;

&lt;p&gt;Let’s get hacking!&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 1: Create a React app
&lt;/h2&gt;

&lt;p&gt;Open your command terminal, change to any directory of your choice, use the following command to create a new React app and name it redux-tutorial&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm create-react-app reduxtutorial
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, cd into the newly created app in the code editor of your choosing. In this tutorial, I’ll be using VS Code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 2: Install all the packages we need
&lt;/h2&gt;

&lt;p&gt;Next, we will be installing all the packages we need to create and test our redux store:&lt;/p&gt;

&lt;p&gt;1) react-redux and redux/toolkit packages to install the redux store in our React app&lt;br&gt;
2) axios for API calls to the endpoint we would be making a GET request to for this tutorial&lt;br&gt;
3) react-router and react-router-dom to create multiple routes in our React app to test if the state is indeed available in all routes and components.&lt;/p&gt;

&lt;p&gt;To install all these required packages, enter the code below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i @reduxjs/toolkit react-redux react-router react-router-dom axios
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Afterwards, start your react app with: npm run start&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 3: Create routes in our React app
&lt;/h2&gt;

&lt;p&gt;Now that we have installed all required packages, let us create the two routes we would be using for the purpose of this tutorial:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Create a pages folder in your src folder and create two files within it: Home.js and Users.js&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Afterwards, copy the following lines of code below into your App.js file&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import './App.css';
import Home from './pages/Home';
import { BrowserRouter,Routes,Route } from 'react-router-dom';
import Users from "./pages/Users"

function App() {
  return (
    &amp;lt;BrowserRouter&amp;gt;
    &amp;lt;Routes&amp;gt;
    &amp;lt;Route path="/" element={&amp;lt;Home/&amp;gt;}/&amp;gt;
    &amp;lt;Route path="/users" element={&amp;lt;Users /&amp;gt;} /&amp;gt;
    &amp;lt;/Routes&amp;gt;
    &amp;lt;/BrowserRouter&amp;gt;
  );
}

export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 4: Create a store in your app at src/store/store.js
&lt;/h2&gt;

&lt;p&gt;Create a store with the following lines 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;import { configureStore } from '@reduxjs/toolkit'

export const store = configureStore({
  reducer: {
    users:{}
  }
})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 5: Provide the Redux store to react so all the components can access it
&lt;/h2&gt;

&lt;p&gt;After you have created your redux store, we need to use a Provider from the React Redux package to make the store available to all our routes and components. To do this, navigate to your index.js file and enter the following lines 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;import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {store } from "./store/store"
import { Provider } from 'react-redux';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  &amp;lt;Provider store={store}&amp;gt;
  &amp;lt;React.StrictMode&amp;gt;
    &amp;lt;App /&amp;gt;
  &amp;lt;/React.StrictMode&amp;gt;
  &amp;lt;/Provider&amp;gt;
);
reportWebVitals();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 6: Create a Redux state Slice
&lt;/h2&gt;

&lt;p&gt;As state values in redux cannot be altered directly within the component, we need to create a State slice that would perform our state changes on our behalf when fired as a function in a react component. As the data we want to store in our state comes from an asynchronous call to an API endpoint, we would be using axios to make the get request and then createAsyncThunk to enable the asynchronous function to fire and store a promise in the state, pending the time when the data arrives. &lt;/p&gt;

&lt;p&gt;The initialState part of the Redux slice contains the initial state of our store. As we are making an asynchronous call, we would be adding a loading state which will change from false to true and true to false depending on whether data has been fetched successfully or not. We would also be using extraReducers to monitor our state change from pending to fulfilled to failed&lt;/p&gt;

&lt;p&gt;To do this, create a new file called user.js in src/store folder and enter the following lines 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;import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

const initialState = {
  value: [],
  loading: false,
};

export const getUsers = createAsyncThunk("users/getUsers", async () =&amp;gt; {
  try {
    const response = await axios({
      method: "GET",
      url: "https://randomuser.me/api/?gender=male&amp;amp;results=3",
      headers: {
        ContentType: "application/json",
      },
    });
    return response.data.results;
  } catch (error) {
    return error;
  }
});

export const usersSlice = createSlice({
  name: "user",
  initialState,
  extraReducers: {
    [getUsers.pending]: (state, action) =&amp;gt; {
      state.loading = true;
    },
    [getUsers.fulfilled]: (state, action) =&amp;gt; {
      state.loading = false;
      state.value = action.payload;
    },
    [getUsers.rejected]: (state, action) =&amp;gt; [(state.loading = "failed")],
  },
});

export default usersSlice.reducer;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 7: Add Redux state slice to the store
&lt;/h2&gt;

&lt;p&gt;Now that we have successfully written the logic to fetch our user data from the API, we need to connect our state slice to the store with the code below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { configureStore } from '@reduxjs/toolkit'
import user from './user'

export const store = configureStore({
  reducer: {
    users:user
  }
})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 8: Dispatch and Fetch Data from the Store in your React Component
&lt;/h2&gt;

&lt;p&gt;Now, we are ready to fire a function within our react component that would fetch the data from the API, store it in the Redux store and make it available across every route. We would be using the useSelector and useDispatch package from Redux to do this. &lt;/p&gt;

&lt;p&gt;Add the following lines of code to the Home.js file created earlier:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React,{useEffect} from 'react'
import { useSelector,useDispatch } from 'react-redux'
import { getUsers } from "./../store/user"
import { useNavigate } from 'react-router'

function Home() {
  const users = useSelector((state) =&amp;gt; state.users.value)
  const dispatch = useDispatch()
  const history = useNavigate()

  useEffect(()=&amp;gt;{
    dispatch(getUsers())
  },[dispatch])

  const gotonextpage = () =&amp;gt;{
    history('/users')
  }

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;div&amp;gt;
        {/* {count} */}
        {users.map((user,i)=&amp;gt;(
            &amp;lt;div key={i}&amp;gt;
                &amp;lt;p&amp;gt;{user.name.title} {user.name.first} {user.name.last}&amp;lt;/p&amp;gt;
                &amp;lt;img src={user.picture.large} alt="img"/&amp;gt;
            &amp;lt;/div&amp;gt;
        ))}
        &amp;lt;button onClick={()=&amp;gt;gotonextpage()}&amp;gt;Go to users&amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default Home

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this stage, your react app should look like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ccWZh1RI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nu8ldgg8mi1pdr8cex7t.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ccWZh1RI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nu8ldgg8mi1pdr8cex7t.PNG" alt="Image description" width="880" height="452"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 9: Check for the state in another Route
&lt;/h2&gt;

&lt;p&gt;By now, you should be seeing a list of 3 names and images on your home screen. This data is being fetched from the API and stored in redux. To confirm that the data is indeed available to other routes, let us add the following lines of code to the users.js file created in Step 3&lt;/p&gt;

&lt;p&gt;In /src/pages/Users.js file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react'
import { useSelector } from "react-redux"

function User() {
    const users = useSelector((state) =&amp;gt; state.counter.value)
  return (
    &amp;lt;div&amp;gt;
        {users.map((user,i)=&amp;gt;(
            &amp;lt;div key={i}&amp;gt;
                &amp;lt;p&amp;gt;{user.name.title} {user.name.first} {user.name.last}&amp;lt;/p&amp;gt;
                &amp;lt;img src={user.picture.large} alt="img"/&amp;gt;
            &amp;lt;/div&amp;gt;
        ))}
    &amp;lt;/div&amp;gt;
  )
}

export default User

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you followed all the steps correctly, you should be seeing the same list of users being displayed on the home screen on the users.js screen as well when you navigate to it by clicking the “Go to users” button on the home page.&lt;/p&gt;

&lt;p&gt;[BONUS] Step 10: Install the Redux Devtools extension in Chrome&lt;/p&gt;

&lt;p&gt;To properly track all your dispatches and state management in Redux, you can install the Redux Devtool extension to view changes being made to your state in real-time. Here is a screenshot of what the state for the tutorial we just did looks like: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--FxnvUsDP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nilli77b7dgnqdzjlsb5.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--FxnvUsDP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nilli77b7dgnqdzjlsb5.PNG" alt="Image description" width="880" height="447"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this tutorial, we were able to successfully make GET requests to an API, store the data fetched from the response within our store and make this data available to all the routes and components in our React app. You can view the repo for the code &lt;a href="https://github.com/Toheeb-Ojuolape/redux-tutorial-article"&gt;here&lt;/a&gt; and meddle with it as much as you want. &lt;/p&gt;

&lt;p&gt;Happy Hacking  ✌&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>redux</category>
      <category>api</category>
    </item>
  </channel>
</rss>
