<?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: Michele</title>
    <description>The latest articles on DEV Community by Michele (@demicdev).</description>
    <link>https://dev.to/demicdev</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%2F518955%2Fd1586929-6026-4b02-b897-d8e69ffd57d4.png</url>
      <title>DEV Community: Michele</title>
      <link>https://dev.to/demicdev</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/demicdev"/>
    <language>en</language>
    <item>
      <title>Easily fetch data: react-api-hook</title>
      <dc:creator>Michele</dc:creator>
      <pubDate>Fri, 30 Apr 2021 21:22:02 +0000</pubDate>
      <link>https://dev.to/demicdev/easily-fetch-data-react-api-hook-2npn</link>
      <guid>https://dev.to/demicdev/easily-fetch-data-react-api-hook-2npn</guid>
      <description>&lt;p&gt;When developing a complex &lt;em&gt;web app&lt;/em&gt; with &lt;strong&gt;React&lt;/strong&gt;, the best thing is modularise and break up the code in smaller components, hooks or functions.&lt;br&gt;
So our code will be &lt;em&gt;easier to maintain&lt;/em&gt; during the time, and it is more readable.&lt;/p&gt;

&lt;p&gt;While reading &lt;a href="https://dev.to/davidkpiano/no-disabling-a-button-is-not-app-logic-598i"&gt;this&lt;/a&gt; blog post, I understood how the usually fetch handling with:&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, { useState } from 'react'

const ComponentWithFetch = () =&amp;gt; {
    const [data, setData] = useState();
    const [isLoading, setIsLoading] = useState();

    const fetchTheData = () =&amp;gt; {
        setIsLoading(true);
        //handle the fetch
    };

    return (
        &amp;lt;button
            onClick={fetchTheData}
            disabled={isLoading}
        &amp;gt;
            Start
        &amp;lt;/button&amp;gt;
    );
};

export default ComponentWithFetch;

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

&lt;/div&gt;



&lt;p&gt;Is basically &lt;strong&gt;wrong&lt;/strong&gt;, because is detached from the &lt;em&gt;logic&lt;/em&gt;, and this is not good.&lt;/p&gt;

&lt;p&gt;So, I decided to make a &lt;strong&gt;package&lt;/strong&gt;, to make this easier, and &lt;strong&gt;simply&lt;/strong&gt; integrate in a project, declaring the hook in the component and passing the datas as parameters.&lt;/p&gt;

&lt;p&gt;All the states of the fetch will be executed separately, in an independent logic, handled by &lt;em&gt;useReducer&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;It is also possible to &lt;em&gt;cancel&lt;/em&gt; the request and the state will update with &lt;code&gt;inAbort&lt;/code&gt; and then &lt;code&gt;canceled&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  To install the package:
&lt;/h3&gt;

&lt;p&gt;Go to the root of your React Project and, on the terminal, write:&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 react-api-hook
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  How to use the package
&lt;/h3&gt;

&lt;p&gt;Now, you can use the package in any component:&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 useAPIHook from  "react-api-hook";

function  App()  {
    const  [state,  send,  cancel]  =  useAPIHook(
        "https://jsonplaceholder.typicode.com/posts",
        {  method:  "GET"  },
    );

    useEffect(()  =&amp;gt;  {
        if (status.status  ===  "success") {
            console.log(status.data);
            //status.data.json() for the body of response  
        }
        if(status.status  ===  "failure") {
            console.log(status.error);
        }
    }, [status]);

    return (
        &amp;lt;div  className="App"&amp;gt;
            &amp;lt;header  className="App-header"&amp;gt;
                &amp;lt;div&amp;gt;{status.state}&amp;lt;/div&amp;gt;
                &amp;lt;div&amp;gt;
                    &amp;lt;button  onClick={send}&amp;gt;start fetching&amp;lt;/button&amp;gt;
                    &amp;lt;button  onClick={cancel}&amp;gt;stop fetching&amp;lt;/button&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;/header&amp;gt;
        &amp;lt;/div&amp;gt;
    );
}

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

&lt;/div&gt;



&lt;p&gt;You will see in the console the response and, on the screen, the status of the request.&lt;/p&gt;

&lt;p&gt;Thanks for reading! &lt;em&gt;I'm open to any pull request or suggestions in the comment!&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;a href="https://www.npmjs.com/package/react-api-hook"&gt;Package link&lt;/a&gt;
&lt;/h3&gt;

</description>
      <category>react</category>
      <category>api</category>
      <category>typescript</category>
      <category>hook</category>
    </item>
    <item>
      <title>Custom complex React Context and TypeScript</title>
      <dc:creator>Michele</dc:creator>
      <pubDate>Wed, 28 Apr 2021 18:10:36 +0000</pubDate>
      <link>https://dev.to/demicdev/custom-complex-react-context-and-typescript-1l1k</link>
      <guid>https://dev.to/demicdev/custom-complex-react-context-and-typescript-1l1k</guid>
      <description>&lt;p&gt;One of the fundamental aspects when developing a &lt;em&gt;website&lt;/em&gt;, an &lt;em&gt;application&lt;/em&gt; or simply a program, is the use of components that are as reusable as possible, as the &lt;strong&gt;DRY&lt;/strong&gt; (&lt;em&gt;Don't repeat yourself!&lt;/em&gt;) rule explains.&lt;/p&gt;

&lt;p&gt;When developing a web app, especially if it is very &lt;em&gt;complex&lt;/em&gt;, it is very important to follow this approach, in order to be able to maintain all the components and functions in a much simpler way.&lt;br&gt;
In this article, we're going to see how React Context can help us in sharing values in all the children of the context and how to create custom and more complex ones (with &lt;strong&gt;hooks&lt;/strong&gt;, &lt;strong&gt;reducers&lt;/strong&gt;, &lt;strong&gt;memoization&lt;/strong&gt;). In addition, we will also add strong &lt;strong&gt;TypesScript&lt;/strong&gt; support.&lt;/p&gt;
&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Create the project&lt;/li&gt;
&lt;li&gt;Add types&lt;/li&gt;
&lt;li&gt;Create the custom provider&lt;/li&gt;
&lt;li&gt;Create the custom hook&lt;/li&gt;
&lt;li&gt;Implement the provider&lt;/li&gt;
&lt;li&gt;Handle the logic&lt;/li&gt;
&lt;li&gt;Dispatch the values&lt;/li&gt;
&lt;li&gt;Epilogue&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  Create the project &lt;a&gt;&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;First, let's create the project, through CRA:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npx create-react-app example --template typescript&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;And then in /src/contexts (create if doesn't exists) we create &lt;code&gt;userContext.tsx&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;import React, { useContext, createContext, useMemo, useReducer } from "react";

const UserContext = createContext();

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  Add types
&lt;/h3&gt;

&lt;p&gt;Next, we add the types of both the context and the reducers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface ContextInterface {
  id?: string;
}

interface ActionInterface {
  type: setUser
  payload: ContextInterface;
}

type DispatchInterface = (action: ActionInterface) =&amp;gt; void;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And then we add these interfaces to UserContext:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const UserContext = createContext&amp;lt;
  | {
      state: ContextInterface;
      dispatch: DispatchInterface;
    }
  | undefined
&amp;gt;(undefined);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We give it an initial value of &lt;code&gt;undefined&lt;/code&gt;, so that later, when we create the provider, we'll pass the reducer to it.&lt;/p&gt;

&lt;h3&gt;
  
  
  Create the custom provider &lt;a&gt;&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;But first, we're going to create the reducer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const reducerUser = (
  state: ContextInterface,
  action: ActionInterface
): ContextInterface =&amp;gt; {
  switch (action.type) {
    case "setUser":
      return { ...state, id: action.payload.id };
    default:
      throw new Error("Invalid action type in context.");
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's now create the custom provider of the &lt;code&gt;userContext&lt;/code&gt; and also declare the reducer, which we will pass as a &lt;em&gt;value&lt;/em&gt; to the provider:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const UserProvider: React.FC = ({ children }) =&amp;gt; {
  const [state, dispatch] = useReducer(reducerUser, {});

  const memoizedUser = useMemo(() =&amp;gt; ({ state, dispatch }), [state, dispatch]);

  return (
    &amp;lt;UserContext.Provider value={memoizedUser}&amp;gt;{children}&amp;lt;/UserContext.Provider&amp;gt;.
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In case our context is very complex and the value needs to be updated often, I suggest to use &lt;strong&gt;useMemo&lt;/strong&gt;, so React won't do any &lt;em&gt;re-rendering&lt;/em&gt; in case the value is equal to the previous one.&lt;br&gt;
In case the context is very simple (like in this case), it's not essential to do this, on the contrary, &lt;strong&gt;using useMemo when you don't need it, leads to lower performance.&lt;/strong&gt; It is shown here as an example only.&lt;/p&gt;
&lt;h3&gt;
  
  
  Create the custom hook &lt;a&gt;&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;Now, let's create our custom hook that will allow us to fetch the id of the user from the children of the context.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const useUser = () =&amp;gt; {
  const user = useContext(UserContext);

  return user;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, user, will contain &lt;strong&gt;state&lt;/strong&gt; and &lt;strong&gt;dispatch&lt;/strong&gt;, with which we're going to &lt;em&gt;display&lt;/em&gt; and &lt;em&gt;update&lt;/em&gt; the user id.&lt;/p&gt;

&lt;p&gt;And finally, we export everything:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export { UserProvider, useUser };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Implement the provider &lt;a&gt;&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;Let's move to &lt;code&gt;App.tsx&lt;/code&gt; and implement what we just created. Let's wrap everything inside our context:&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 { Dashboard, UserProvider } from "./index.d";

const App: React.FC = () =&amp;gt; {
  return (
    &amp;lt;UserProvider&amp;gt;
      &amp;lt;Dashboard /&amp;gt;
    &amp;lt;/UserProvider&amp;gt;
  );
};

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  Handle the logic &lt;a&gt;&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;In &lt;code&gt;Dashboard.tsx&lt;/code&gt;, we will import the &lt;code&gt;useUser&lt;/code&gt; hook created earlier and with that we will check the id. If it isn't undefined, then, it will show the login.&lt;br&gt;
Otherwise, it will show a simple dashboard that shows the user the user id:&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 { useUser, Login } from "../index.d";

const Dashboard: React.FC = () =&amp;gt; {
  const userContext = useUser();

  if (!userContext!.state.id) return &amp;lt;Login /&amp;gt;;

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;Dashboard&amp;lt;/h2&amp;gt;&amp;gt;

      &amp;lt;p&amp;gt;
        User logged with &amp;lt;em&amp;gt;id&amp;lt;/em&amp;gt;: &amp;lt;strong&amp;gt;{userContext!.state.id}&amp;lt;/strong&amp;gt;
      &amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As soon as we open the page, the id will obviously be &lt;code&gt;undefined&lt;/code&gt;, because no one logged in.&lt;br&gt;
So, we'll be shown the login page (in &lt;code&gt;Login.tsx&lt;/code&gt;):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fv7x4w15uiw8q5s7kqjs6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fv7x4w15uiw8q5s7kqjs6.png" alt="Styled login page" width="800" height="1015"&gt;&lt;/a&gt;&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, { useState } from react;
import { useUser } from "../index.d";

const Login: React.FC = () =&amp;gt; {
  const [username, setUsername] = useState&amp;lt;string&amp;gt;("");
  const [password, setPassword] = useState&amp;lt;string&amp;gt;("");

  const handleLogin = (e: React.FormEvent&amp;lt;HTMLFormElement&amp;gt;) =&amp;gt; {
    e.preventDefault();
    loginTheUser().then((id) =&amp;gt; {});
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;h1&amp;gt;Login&amp;lt;/h1&amp;gt;.
        &amp;lt;form onSubmit={handleLogin}&amp;gt;
          &amp;lt;div&amp;gt;
            &amp;lt;input
              id="user"
              type="text"
              value={username}
              placeholder="Username"
              onChange={(e) =&amp;gt; setUsername(e.target.value)}
            /&amp;gt;
          &amp;lt;/div&amp;gt;
          &amp;lt;div&amp;gt;
            &amp;lt;input
              type="password"
              id="password"
              value={password}
              placeholder="Password"
              onChange={(e) =&amp;gt; setPassword(e.target.value)}
            /&amp;gt;
          &amp;lt;/div&amp;gt;
          &amp;lt;button type="submit"&amp;gt;sign in&amp;lt;/button&amp;gt;
        &amp;lt;/form&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  Dispatch the values &lt;a&gt;&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;To make the context work, however, you must import the custom hook:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleUserContext = useUser();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And finally, we add the dispatch call that updates our state:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleLogin = () =&amp;gt; {
    loginTheUser().then((id) =&amp;gt;
      handleUserContext!.dispatch({ type: "setUser", payload: { id: id } })
    );
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ok, now, after logging in, the message we wrote will appear. &lt;br&gt;
It seems to be working, perfect! But what if you want to pass it between &lt;em&gt;multiple components&lt;/em&gt;? Do you have to pass it as a prop in the children?&lt;/p&gt;

&lt;p&gt;No, otherwise the point of Context would be lost. To display or update the id, just call the hook from a UserContext child and use the state and dispatch variables to update it.&lt;br&gt;
Simple, isn't it?&lt;/p&gt;

&lt;h3&gt;
  
  
  Epilogue &lt;a&gt;&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;Now, before we wrap it up, we can install &lt;em&gt;styled-components&lt;/em&gt; and add some simple (and ugly) &lt;em&gt;CSS&lt;/em&gt; to our project and, to see it finished, I refer you to the &lt;a href="https://github.com/demic-dev/React-Custom-Context"&gt;repo on Github&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This here is just a basic example, but it can come in very handy when developing complex web apps, where there are some data that need to be passed in all children (such as authentication, or global settings, like dark mode).&lt;/p&gt;

&lt;p&gt;Thanks for reading this article! If you encountered any errors or if you want to add something, leave a comment!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/demic-dev/React-Custom-Context"&gt;Github repo.&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>typescript</category>
      <category>javascript</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>First approach to mobile design</title>
      <dc:creator>Michele</dc:creator>
      <pubDate>Wed, 30 Dec 2020 23:11:59 +0000</pubDate>
      <link>https://dev.to/demicdev/first-approach-to-mobile-design-1bac</link>
      <guid>https://dev.to/demicdev/first-approach-to-mobile-design-1bac</guid>
      <description>&lt;p&gt;Some months ago, as a developer, I got caught by designing systems and guidelines, because in all my projects I always tried to have, in the end, a well cared graphic. But I always had bad results, and when I built some mobile apps or website, I always used frontend framework (such as Bootstrap) or pre-built components (I use React Native) to have some sufficient result.&lt;/p&gt;

&lt;p&gt;So, I decided to start studying a bit deeper how design is chosen and made, when starting building an application.&lt;/p&gt;

&lt;p&gt;During Black Friday I bought a course that focuses only on design from the point-of-view of developers.&lt;/p&gt;

&lt;p&gt;After some episode of the course I decided to start dive in this "world" and so I downloaded Figma and started a new project.&lt;/p&gt;

&lt;p&gt;I started from scratch, with a blank page so I had no idea of what to design.&lt;/p&gt;

&lt;p&gt;I was with zero inspiration and a lot of will to start, so I opened Dribbble and I started searching for some design ideas. &lt;/p&gt;

&lt;p&gt;Then finally I understood that if I would continue searching the "perfect idea", I would never start and inspiration comes by doing, also.&lt;/p&gt;

&lt;p&gt;So, in the end, I decided to create the template of an eBooks app. I created a simple wireframe of the main screen and then I decided to create the templates of the Main Screen and Product Screen.&lt;/p&gt;

&lt;p&gt;Here's my results.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F4j84wgosl58i7wi1cvdn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F4j84wgosl58i7wi1cvdn.png" alt="Alt Text" width="800" height="811"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I wanted to share this to receive some feedbacks about this, especially if there is someone that know this arguments and some design techniques or if something is wrong (such as colors or fonts). I'm still a newbie about this argument and I have a lot to learn, so any feedback will be appreciated!&lt;/p&gt;

&lt;p&gt;Also, for the next future another challenge for me is to port to React Native code this template, after adjusting something, because could be very useful for learning new styles techniques.&lt;/p&gt;

</description>
      <category>figma</category>
      <category>design</category>
      <category>mobile</category>
    </item>
  </channel>
</rss>
