<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Marco Lancellotti on Medium]]></title>
        <description><![CDATA[Stories by Marco Lancellotti on Medium]]></description>
        <link>https://medium.com/@lancellotti-marco?source=rss-4e1214375ade------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5G8xpXTJ9FeeLmqg2WVrKA.jpeg</url>
            <title>Stories by Marco Lancellotti on Medium</title>
            <link>https://medium.com/@lancellotti-marco?source=rss-4e1214375ade------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 18:39:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lancellotti-marco/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Wiring Up a Redux Store in React Apps]]></title>
            <link>https://lancellotti-marco.medium.com/wiring-up-a-redux-store-in-react-apps-25e1e2224b31?source=rss-4e1214375ade------2</link>
            <guid isPermaLink="false">https://medium.com/p/25e1e2224b31</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[redux-thunk]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Marco Lancellotti]]></dc:creator>
            <pubDate>Mon, 30 Nov 2020 08:39:46 GMT</pubDate>
            <atom:updated>2020-11-30T08:39:46.140Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*nj5zP-tONts7cSvXRqEcAQ.png" /></figure><p>In this article we will go through the process of setting up a <a href="https://redux.js.org/">Redux</a> Store inside a React App. Even though the Context API are now available out of the box in React, the use of Redux is still widespread and maintains its charme and advantages. I thought it was a good idea to have an article to use as a reminder of the steps needed to <strong>manually </strong>put in place a Redux Store in order to start with new React/Redux projects faster!</p><h4>What you should know to follow</h4><p>In this tutorial I shall assume you already know about React and its fundamentals (<strong>components</strong>, <strong>state</strong>, <strong>props</strong>) and that you already know what Redux is and how it works. You should also know already what <strong>reducers</strong>, <strong>actions</strong> and <strong>action creators </strong>are. Nevertheless, we will take a few minutes to refresh our memory about what Redux is, and how it works.</p><h4>Important Note</h4><p>As of today it is possible to initialize a “<em>redux-ready” </em>React app with tcreate-react-app and<em> </em>the <em>Redux-JS template</em> option, in order to make use of the <a href="https://redux-toolkit.js.org/"><strong>Redux Toolkit</strong></a><strong> </strong>package, intended to provide a standardized way to structure a React/Redux project and avoid boilerplate code. However, the purpose of this guide is to show how to manually implement a Redux Store and its middlewares, so we won’t use Redux Toolkit here.</p><h3>What Redux is and how it works</h3><p>according to its official website:</p><blockquote>Redux is a predictable state container for JavaScript apps.</blockquote><p>The basic idea behind Redux, is to have an immutable big object called <strong>Redux</strong> <strong>Store</strong> which represents the only source of truth in the whole application. This object can be modified only through some <strong>predictable</strong> (<em>predefined</em>) actions.</p><p>A <strong>store </strong>is composed by different <strong>reducers. </strong>A <strong>reducer </strong>is a function whose purpose is to manipulate a small set of data representing a specific aspect of our application business in a form of an object called state.State can only be modified in a predictable way through some predefined <strong>actions</strong>. An <strong>action </strong>is basically an object that by convention has 2 properties:</p><ul><li>type a string that defines its “purpose”, used by the reducer function to detect whether to change the state or not and how to change it.</li><li>payload an object containing the data that needs to be used by the reducer function while modifying the state. It is an optional parameter since sometimes no payload is needed.</li></ul><pre>{type: &#39;ADD_ITEM&#39;, payload: {id: 1, name: &#39;pencil&#39;}}</pre><p>These actions need to be <strong>dispatched </strong>(<em>triggered) </em>by some functions, which we define as <strong>action creators</strong>. Once the action is dispatched, it gets passed to all the reducers of the state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68e76726a498bfe6a686cb68415cc02a/href">https://medium.com/media/68e76726a498bfe6a686cb68415cc02a/href</a></iframe><p>The reducers will have some instruction on how to modify their state object according to different action types.What I described so far can be achieved without any particular library. In fact, even inside a React application, we will define our actions, action creators and reducers with plain JS objects and functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/272073cd69c4b590371de0f8f30ba7e3/href">https://medium.com/media/272073cd69c4b590371de0f8f30ba7e3/href</a></iframe><p>What we have seen so far can be achieved without any particular library. In fact, even inside a React application, we will define our actions, action creators and reducers with plain JS objects and functions.</p><p>It is only when we need to wrap up all our reducers and action creators together that we will make use of the <strong>Redux</strong> library. More precisely, we will use a few special functions from the library:</p><ul><li>combineReducers useful to put together all our reducers into a single object</li><li>createStore which takes the object created through combineReducer and returns a Redux Store.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c63054d5c084383e87f9506f2192015e/href">https://medium.com/media/c63054d5c084383e87f9506f2192015e/href</a></iframe><p>The benefit of combining the reducers into a single store, is that every time an action is passed to store.dispatch(), it is then passed through all of our reducers. Once all the reducers have returned their state, they are combined again to form the updated Redux Store.</p><p>We can summarize the flow with the following schemas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*rY1N2B9wVzmGpCd8vo1cZw.png" /><figcaption>A Redux Store is created by combining the reducers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*B8_ysYK9D3nyPPcWNAqTsg.png" /><figcaption>The Redux Store is modified by using the Actions flow</figcaption></figure><p>Keeping in mind what we have just sais, let’s see how we integrate the Redux pattern inside a React Application.</p><h3>Redux in React</h3><p>The first thing I want to point out, is that when we talk about Redux in React we basically talk about the <a href="https://www.npmjs.com/package/react-redux">React-Redux</a> library.</p><p>It is this library that allows Redux and React to communicate with each other properly and makes it easier for us to read the store data or dispatch our functions.</p><p>As stated in the introduction, we are not going to use the ReduxToolkit for this article, so assuming we created our app with create-react-app and no particular template, we must install the Redux library and the React-Redux library manually:</p><pre>npm install --save redux react-redux</pre><h4>1- Defining reducer and action creators</h4><p>Before we actually use any function from the redux or react-redux library we will have to create our action creators and reducers. I usually structure my projects in order to have a reducers and actions folders where I define all my functions separated by topic and then barrel them into a single index.js file to be exported.</p><h4>2- Combining reducers</h4><p>Most importantly, make sure that insidereducer/index.js file you combine all your reducers with redux’s combineReducers function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c63054d5c084383e87f9506f2192015e/href">https://medium.com/media/c63054d5c084383e87f9506f2192015e/href</a></iframe><p>Keep in mind that the key you provide inside the combineReducers argument, will be used as a prop inside the Redux Store.</p><h4>3 - Creating the State and wiring up the Provider</h4><p>We must make sure to create a Redux Store out of our combined reducers and provide it throught our application.</p><p>To create the store, all we have to do is to import our combined reducers and call the createStore function provided by the Redux library.</p><p>To make the store available to all our components, we will make use of the <strong>Provider</strong> component of the React-Redux library. This component expects a store as a props and it is intended to wrap our entire application, namely, our &lt;App /&gt; component!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e607ba91efcb613a2505b96685bcb98c/href">https://medium.com/media/e607ba91efcb613a2505b96685bcb98c/href</a></iframe><p>Once we have wrapped our main component inside the provider, all our nested components will be able to get access to our state data!</p><h3>Accessing the store</h3><p>We have said we are now able to reach our state from all the components in our app but we must see how. There are actually 2 different methods to read the data from the store: the <a href="https://react-redux.js.org/api/connect"><strong>connect</strong></a> function and the <a href="https://react-redux.js.org/api/hooks#useselector"><strong>useSelector </strong></a>hooks.</p><h4>Option 1: Connect &amp; mapStateToProps functions.</h4><p>The most traditional way to get access to the store data from one of our components, is to pass the entire component to the connect function from react-redux.</p><p>The connect function will return a copy of the component entirely connected to the store. However, in order for the component to properly read the store data, we must first provide an important argument to the connect function: mapStateToProps.</p><p><strong>mapStateToProps </strong>is a function used for selecting the part of the data from the store that the connected component needs. This function should be passed as the first argument to connect, and will be called every time when the Redux store state changes.</p><p>mapStateToProps is called with the entire <strong>store</strong> as its first and only argument and should return an object where all the keys represent the mapped props from the store, to be consumed in the reducer. Let’s try to make an example:</p><p>If we want to read our list of items from our store inside of a <em>MyList </em>component, this is what we would do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03ea4be0aa9f5ad44de5764cd837e1f4/href">https://medium.com/media/03ea4be0aa9f5ad44de5764cd837e1f4/href</a></iframe><p>Note how the object returned by mapStateToProps is defining the name of the props the component will use to access the data.</p><p>An important aspect is that the connect function can be used for both class and functional components.</p><h4>Option 2: useSelector (functional components only)</h4><p>In the last version of React-Redux, hooks are available for us to use inside our functional components.</p><p>In order to read data from the Redux Store, we may use the <a href="https://react-redux.js.org/api/hooks#useselector"><strong>useSelector </strong></a>hook. The useSelector hook is conceptually corresponding to mapStateToProps but it has some differences, the most important being:</p><ul><li>It can be used only inside functional components.</li><li>It can return <strong>any value, </strong>not necessarily an object.</li><li>It can be declared <strong>multiple times</strong> inside the component.</li><li>It is called every time the components re-render but <strong>only if its returned value has changed.</strong></li></ul><p>Its use is however very similar to mapStateToProps, since its mandatory first argument is a function that receives the entire store, just as in mapStateToProps , with the difference, as already said that it can return any value. Let’s see the same example with useSelector:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1472b1be76b79fd2e929c16a2643c8de/href">https://medium.com/media/1472b1be76b79fd2e929c16a2643c8de/href</a></iframe><h3>Dispatching the actions and modifying the store</h3><p>Now that we have seen how to read data from our store, let’s focus on how we can perform changes on it, that is, how to dispatch our action creators!</p><p>If you have understood how Redux works, it will be clear to you that in order to trigger an action and send it to all the reducer in the store, what we need is to pass an action creator to the store.dispatch() function.</p><p>But how can we access the dispatch function from a component? Well, here is where the React-Redux magic comes into place and again, we have 2 different ways!</p><h4>Option 1: Connect &amp; mapDispatchToProps</h4><p>Very similarly to what we have seen with mapStateToProps, the <strong>connect</strong> function allows us to map also the actions creators to the component’s props.</p><p>The trick is very simple: connect can accept a <strong>second parameter</strong> called, guess what? <strong>mapDispatchToProps.</strong></p><p>mapDispatchToProps needs to be an object whose keys will be mapped to a prop inside a component. Each key of this object must be a function that eventually returns an <strong>action</strong>, that is, an object with type (mandatory) and payload (optional) arguments.</p><p>Let’s see a very simple example, extending the previous <em>MyList.js </em>component. We will import our previously declared removeItemaction creator from its file, and map it to a delete property inside the component. We will then add a button for each item of the list, and try to call our delete property with the id of the item as its argument:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bc1c093857d97953893a77f63aa7a43/href">https://medium.com/media/0bc1c093857d97953893a77f63aa7a43/href</a></iframe><p>IMPORTANT NOTE: in some cases we only want to use action creators inside a component, regardless of the rest of the store. In those cases, you should provide null as the first argument to connect and mapDispatchToProps as a second argument!</p><h4>Option 2: useDispatch (functional components only)</h4><p>An even simpler approach is available to us inside of functional components, thanks to the <a href="https://react-redux.js.org/api/hooks#usedispatch"><strong>useDispatch</strong></a> hook.</p><p>This hook provides a direct reference to the store.dispatch() function, making its use really straightforward.</p><p>Of course, you only need to call the hook <strong>once</strong> inside a single component and then use its reference with different action creators.</p><p>Let’s see how our example <em>MyList </em>looks with this approach:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40e3a353db167a4b07ba36a70461fcac/href">https://medium.com/media/40e3a353db167a4b07ba36a70461fcac/href</a></iframe><h3>Handling async actions with Redux-Thunk</h3><p>There we go, my friends! We have our store in place now, but we need to handle a little issue that we may have if we need to consume some API inside our actions creators.</p><h4>The problem</h4><p>Remember: action creators are supposed to <strong>return a plain object. </strong>But when we make use of asynchronous code, we are breaking this rule and Redux is going to show a very big error screen to us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*NfTV_TjSDSMMADYR-5VjEQ.png" /><figcaption>If we perform an async call inside an action creator, this is what we run into.</figcaption></figure><h4>The solution</h4><p>In order to bypass this issue, we will make use of a middleware called <strong>Redux Thunk</strong>.</p><p>What Redux thunk does, is putting itself in the middle every time an action creator is <strong><em>called </em></strong>and performs a check on what is returned; if the return value is an object, it will then call store.dispatch for us.</p><p>If the return value is a function, it will prevent redux from breaking and instead will provide a new functions with 2 arguments out of the box:</p><ul><li>the <strong>dispatch </strong>function, that we can use to dispatch the action once we performed all our async code or other logics</li><li>a <strong>getReduxStore </strong>function, that we can use to inspect the whole content of the store!</li></ul><p>Let’s see how to implement this. We can install it with</p><pre>npm i --save redux-thunk</pre><p>We can now move to our index.js file and import thunk from redux thunk and applyMiddleware from the redux library.</p><p>All that remains to wire up Redux-Thunk is to pass thunk as the first argument to applyMiddleware and applyMiddleware as the second argument to createStore . From now on, all our actions will be handled by the thunk middleware.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f1bf4e021fa7b9940307c0630bc8f3a/href">https://medium.com/media/2f1bf4e021fa7b9940307c0630bc8f3a/href</a></iframe><p>But remember: all Redux Thunk does is allow our action creators to return a function and provide that function with the store.dispatch function to be called whenever our async functions are finished. So let’s see a proper way to handle asynchronous tasks inside our action creators:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/421b6057db44baa1abdb5383f5355026/href">https://medium.com/media/421b6057db44baa1abdb5383f5355026/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25e1e2224b31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remapping backtick (`) and tilde (~) keyboard shortcuts on Windows]]></title>
            <link>https://lancellotti-marco.medium.com/remapping-backtick-and-tilde-keyboard-shortcuts-on-windows-e2923e455817?source=rss-4e1214375ade------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2923e455817</guid>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[tilde]]></category>
            <category><![CDATA[backtick]]></category>
            <category><![CDATA[shortcut-keys]]></category>
            <category><![CDATA[shortcuts]]></category>
            <dc:creator><![CDATA[Marco Lancellotti]]></dc:creator>
            <pubDate>Mon, 16 Nov 2020 16:56:56 GMT</pubDate>
            <atom:updated>2024-09-09T13:12:42.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6l48eSdgsEfJQUgow0nLRw.jpeg" /></figure><h3>The problem</h3><p>If you are a developer and work with Windows, it is very likely that at somepoint in time, you faced with an annoying little issue: typing a backtick and/or a tide in your code.</p><p>Maybe you use the new ES6 syntax and needed the backtick to interpolate your variables inside a string. Or maybe, you were trying to set up a CSS sibling selector.</p><p>In any case, typing these characters on Windows is quite uncomfortable. If you are lucky enough to have the numberpad on your pc, then you could use the default shortcuts provided by windows… if you can remember them!</p><p>The <strong>native backtick shortcut</strong> on Windows is Alt + 96 , whereas the native <strong>shortcut for the tilde</strong> is Alt + 126 .</p><p>The important point is that the numbers for these shortcuts must be typed on the number pad and, alas, not all computers (especially the small laptops) have the number pad on their keyboard, making it impossible to use them, forcing users to find the desirred characters somewhere on the internet or in other parts of code and copy/paste them, a very annoying procedure.</p><h3>The solution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xm9r18ih-Hf6EoRXSQUekw.png" /></figure><p>Have you ever heard of <a href="https://www.autohotkey.com/"><strong>AutoHotKey</strong></a><strong>?</strong></p><blockquote>AutoHotkey is a free, open-source scripting language for Windows that allows users to easily create small to complex scripts.</blockquote><p>Well, this little program will save your life! You can download it free from its <a href="https://www.autohotkey.com/"><strong>official website</strong></a><strong>, </strong>and by doing so, you will be able to write and run some code, to remap all of your keyboard shortcuts.</p><p>Let’s see how ca we settle our <strong>tilde </strong>and <strong>backtick </strong>comfortable shortcuts thanks to AutoHotKey!</p><h4>Installation</h4><p>As stated above, we can install it from <a href="https://www.autohotkey.com/"><strong>https://www.autohotkey.com/</strong></a>. We just need the Standard Installation. Once the wixard ends the installation, there’s no need to run the program.</p><h4>Create a .ahk file</h4><p>The main step is to write the script to bind our desired key combinations to print both ~and &#39; characters.</p><p>What I want to acheive is the following shortcuts:</p><ul><li>AltGr + - prints ~</li><li>AltGr + &#39; prints `</li></ul><p><em>If you want to use different key combinations, please refer to the </em><a href="https://www.autohotkey.com/docs/AutoHotkey.htm"><em>AutoHotKey docs</em></a></p><p>Let’s start by creating a startup.ahk file on your desktop. You can edit it with your code editor or with the default Windows Notepad. Now, type this:</p><pre>#Requires AutoHotkey v2.0<br><br>&lt;^&gt;!vkDD::Send &quot;~&quot;<br>&lt;^&gt;!&#39;::Send &quot;``&quot;</pre><p>Let’s have a look at the script:</p><p>There are 2 lines of code, the first for the <em>tilde</em> and the second for the <em>backtick. </em>The first part of each block represents the key combinations in AutoHotKey language:</p><p>So in the first line the “&lt;^&gt;!” represents the AltGr key, vkDDrepresents the - key, while the :: represent the end of the key combination. In the second block, the vkDD is substituted by the &#39; as we decided to use AltGr + &#39; for the backtick shortcut.</p><p>The second part represents what we want the shortcut to return. In the first line we used Send &quot;~&quot; (yes, you will have to copy paste the tilde for now); in the second we must use Send and include two backtick (&quot;``&quot;)because the backtick is a reserved character in AutoHotKey, so we need to escape it.</p><p>Now, save the file, close it and double click on it. Now <strong>our shortcuts will magically work in every program on the PC!</strong> This means not only your into your favourite code editor but also in the web browser, on Microsoft Word, in the e-mails and so on… at least untill we shut down the pc! :/</p><h4>Automatically execute the script at PC startup</h4><p>Although it is possible to put the file on the desktop and double click on it everytime we turn on the computer, there is a much better way to make our shortcut automatically available at all time.</p><p>All you need to do is moving this startup.ahk file, inside this folder:</p><pre>C:\Users\YOUR_USER\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup</pre><p>Remember to replace YOUR_USER above with your user name. Also note that the AppData is a <strong>hidden folder, </strong>so if you don’t see it inside your user’s folder be sure to <a href="https://support.microsoft.com/en-us/windows/view-hidden-files-and-folders-in-windows-10-97fbc472-c603-9d90-91d0-1166d1d9f4b5">set the hidden folders as visible</a>.</p><p>The Startup folder is a special folder whose files will be executed when we access Windows. Moving our file inside there, will ensure our script to be ran behind the scene every time we turn on the computer!</p><p><strong>LEGACY</strong></p><p>This is the old code for AutoHotKey Version 1 on Windows 10:</p><pre># AutoHotKey v.1.0<br>&lt;^&gt;!-:: <br>  Send ~<br>Return<br><br>&lt;^&gt;!&#39;::<br>  SendRaw ```<br>Return</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2923e455817" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to migrate a free Wordpress website from Wordpress.com to your own domain]]></title>
            <link>https://lancellotti-marco.medium.com/how-to-migrate-a-free-wordpress-website-from-wordpress-com-to-your-own-domain-f9f12000bda6?source=rss-4e1214375ade------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9f12000bda6</guid>
            <category><![CDATA[hosting]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Marco Lancellotti]]></dc:creator>
            <pubDate>Sun, 01 Nov 2020 07:23:40 GMT</pubDate>
            <atom:updated>2020-11-01T07:24:25.700Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="WordPress" src="https://cdn-images-1.medium.com/max/1024/1*6hzbyWebsgp_3qm74EKwyw.png" /></figure><h3>A common scenario</h3><p>The idea for a new blog or a website comes to your mind and you find yourself driven by the typical enthusiasm of this new project. You want to get started as soon as possible, but you have no experience with domains, hostings and websites in general, so what to do? The solution is a free version of WordPress hosted on wordpress.org: no installation, no complicated stuff, no payments or subscriptions, in other words the perfect deal!</p><p>Yes, but… your website address has that /wordpress.org suffix that doesn’t sound very professional.. but hey, it’s free so you can turn a blind eye after all.</p><p>However, one day you realize your project started to grow, your ideas are more clear and you want to scale up! More needs arise and surfing on the web you will discover a huge amount of plugins that would fit perfectly into your website, but.. oh-oh: <strong>plugins are not available on your free version of WordPress.</strong></p><h3>The solution(s):</h3><p>As a matter of fact, the easiest solution is to upgrade to the WordPress Business plan. You can buy your own domain directly from WordPress and get finally rid of that <em>wordpress.org, </em>while you keep all your work and continue working as usual, being also able to install third party plugins without loosing anything of what you’ve done.</p><p>Nevertheless, you may want to host your own website separately. Maybe you found a cheaper deal for it or you already have your own domain or whatever other reason you can think of. The only problem is: you don’t want to lose your work and you don’t know how to migrate your wordpress site.</p><p>Now is when this tutorial comes into your help!</p><p><strong><em>Iportant Note: </em></strong><em>importing your contents will </em><strong><em>NOT </em></strong><em>import your theme!</em></p><h3>Requirements</h3><p>There are no particular knowledge requirements to follow this tutorial. On the technical side, the only thing you need is to have a <em>domain</em> and a <em>hosting</em> of your own, as our purpose is precisely to move WordPress instance, hosted freely on <a href="https://wordpress.com/">wordpress.com</a> to a domain of your own.</p><p>If you have your domain and hosting then you’re ready to go on with our migration tutorial!</p><h3>Step 1 — A clean installation of WordPress</h3><p>As a first step of the process, you need to have on your domain a fresh WordPress, that is, a brand-new installation of WordPress with no content except for the name of the website itself and an administration account.</p><p>You can have a new WordPress already installed on your hosting by your service provider or you may want to install it manually by yourself. If you don’t know how to install a new WordPress website, stop this tutorial here and read my article on <a href="https://lancellotti-marco.medium.com/how-to-manually-install-wordpress-on-your-own-domain-84046db5ccd5"><strong><em>How to manually install WordPress on your own domain</em></strong></a><strong><em>.</em></strong></p><h3><strong>Step 2 — Export your existing WordPress</strong></h3><p>Now that you have a fresh instance of WordPress on your hosting, it is time to take all the information we need from your current free hosted WordPress on <em>wordpress.com. </em>To do so, just go into your admin panel and in the sidebar, go to <em>Tools &gt; Export .</em></p><p>In this page, click the <em>Export all</em> button as shown in the picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4H8Wzb5NiaiY8GZwrzRUZQ.png" /></figure><p>Wait a few minutes until the export process is finished. You can now click <em>Download </em>on the right side of the success alert. In doing so, you will download a zipped folder, containing one or more .xml files (depending on how much content you have on your website). These files, contain all the information about your website content, including pages, articles, authors and media. Please note it does <strong><em>NOT </em></strong>contain anything related to your website theme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*6j2qYotsVCGeyx35O8oQMg.png" /></figure><h3>Step 3 — Importing your content to the new Website</h3><p>It is now time to bring all our content inside the new website on our domain! First, access the new WordPress with the administrator account. On the sidebar go to <em>Tools &gt; Import.</em></p><p>In this page we will see a list of import options. Since we are moving from WordPress, let’s pick the <em>WordPress</em> option and click the <em>Install Now </em>link to install the official WordPress importer plugin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kLIWL1t_zbdvsd-fnupP1g.png" /></figure><p>Let’s wait a few seconds until a <em>Run Importer</em> link will show up in the same spot and then click it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*V1pHFZVhElvdpdJh3agfMg.png" /></figure><p>We will be asked to upload a file to import our content. Let’s click the browse button and pick the .xml file we downloaded in step 2, then click the <em>Upload file and import</em>. If you have more than one xml file, you will need to repeat this process for each one of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q81Nxxu5WgrwDV5mm_b9Cw.png" /></figure><p>In the next screen, WordPress will look for the authors of the posts we are importing and will ask what to do with each of them. Our choices are: importing the original author, create a new user and assign the articles to it, or assign the posts of the author to an existing author of the new website. Of course, this choice is up to you!</p><p>It is very important to check the <em>Download and import file attachment </em>option before we click the <em>Submit </em>button. This will allow WordPress to import all files and media in the articles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z4ZTuhYuYSxdhMnqEmXz8g.png" /></figure><p>Now, we only need patience. Depending on how much content you are trying to import, the process will take some time, up to 20 minutes in some cases. At the end, we will see a success message, and if you go on the <em>Articles, Pages and Post</em> sections you will see all your content! Have fun!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*0gz3rCkwyB4w0qosC-6_aQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9f12000bda6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to manually install WordPress on your own domain]]></title>
            <link>https://lancellotti-marco.medium.com/how-to-manually-install-wordpress-on-your-own-domain-84046db5ccd5?source=rss-4e1214375ade------2</link>
            <guid isPermaLink="false">https://medium.com/p/84046db5ccd5</guid>
            <category><![CDATA[ftp]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[installation]]></category>
            <category><![CDATA[wordpress]]></category>
            <dc:creator><![CDATA[Marco Lancellotti]]></dc:creator>
            <pubDate>Thu, 22 Oct 2020 08:22:18 GMT</pubDate>
            <atom:updated>2020-10-22T08:45:58.713Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVfM4fnaPtNUkr2R81Dg4A.png" /></figure><p>There we go again, talking about <a href="https://wordpress.org/"><strong>WordPress</strong></a>, the most used CMS in the web! Everyone knows how reliable a WordPress website is and how many possbilities it has to offer thanks to the huge number of third-party plugins out there. It is easy to use, simply to mantain and very fast when it comes to add content!</p><p>WordPress is so widespread that nowadays most of the hosting solutions companies also offer a “WordPress package” providing a pre-installed version of WordPress together with hosting and domain services.</p><p>However, these offers are defintely more expensive than a plain hosting+domain solution, and it is not uncommon that the difference in price is not worthy at all if you know how to manually install a WordPress website by yourself, especially if you think that WordPress itself is totally free.</p><p>For this reason, I’d like to share with you this beginner guide so to show you how simple it is to install WordPress by yourself and save some money!</p><h3>Knowledge Requirements</h3><p>I’ll tell you immediately: <strong>no coding skills are required to follow. </strong>This tutorial is dedicated to total beginners and this is what you need:</p><ul><li>Being able to use a computer. (Unzip folders, copy paste, surf the web, install programs)</li><li>OPTIONAL: Basic knowldge of what a <em>domain </em>and a <em>hosting server </em>are.</li></ul><h4><strong>Domain? Hosting? What? (OPTIONAL)</strong></h4><p>If you know what I am talking about, skip this paragraph!</p><p>Else, if you felt lost reading these terms don’t worry, I’ll explain you what you need to know without going deep into technicalities!</p><p>Basically, when you go to any website, let’s say <a href="http://www.medium.com,/">www.medium.com,</a> you are typing an address on your browser address bar, right? Very well, put it in the simpliest way,<strong> a</strong> <strong>domain is an address on the web</strong>!</p><p>Therefore, if your name is John Doe and you wish to have your blog available at www.johndoe.com then you need to buy the johndoe.com domain. You just need to google “<em>johndoe.com buy domain</em>” and, if the domain is available (meaning it has not been bought by someone else), you will find many companies with different offers for you.</p><p>However, the domain alone is but an address. It’s like buying an empty plot of land. In order to build on your land, you need an <em>hosting server</em>. Allow me a very little bit of technicality here.</p><p>When you visit a website, your browser is showing you some web pages, which are the result of a series of files, coming to your computer from a hosting server. In other words, the <em>hosting server </em>is a computer, located somewhere in the world, that hosts some files in it. In order to have your own website, you will need to buy a piece of the memory in one of these computers. Anytime someone will browse to your <em>domain, </em>then the files will go from your <em>hosting server </em>to the computer that is surfing your website<em>.</em></p><p>Usually, most of the companies provide both <strong><em>domain and hosting</em> </strong>(and it surely is a good idea) but it is entirely possible to buy the two things from separate providers.</p><p>Prices and offers also vary based on how big the space in the <em>hosting server </em>is and by the number of databaes (required to store content and settings on your websites). I understand how difficult could be to approach all the offers but see the next chapter for the minimum technical requirements you need to look for when picking your hosting services<em>.</em></p><h3>Technical Requirements</h3><p>In order for you to be able to install and run a WordPress website, you must ensure that your provider includes in the offer:</p><ul><li>At least one <strong>SQL database</strong></li><li><strong>PHP 7 </strong>installed on the server</li><li>At least <strong>2GB of storage</strong> space (the more you have, the better)</li><li><strong>FTP</strong> Access (A way of connection that allow you to browse the folders in your server)</li></ul><p>When you have purchased your domain and hosting, your provider should send you these information, which are crucial to install Wordpress:</p><ul><li><strong>FTP host</strong> name</li><li><strong>FTP use</strong>r name</li><li><strong>FTP passwor</strong>d</li><li><strong>Database name</strong></li><li><strong>Database username</strong></li><li><strong>Database password</strong></li><li><strong>Database host</strong></li></ul><p>If you miss some of these pieces of information, you can ask support from your service provider!</p><h3>Step 1 — Getting WordPress</h3><figure><img alt="Wordpress.org" src="https://cdn-images-1.medium.com/max/1024/1*iTIKPuF01zdT9435e8D4nQ.png" /></figure><p>As stated above, WordPress is 100% free and it is available for download at <a href="https://wordpress.org/download/">wordpress.org</a>.</p><p>Once you download the .zip file, you can unzip it and navigate inside the unzipped folder until you find awordpress folder with this content:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2HP-4M7rCx1WlrTWBY-bRA.png" /></figure><p>Let’s leave this folder aside for now and let’s proceed to step 2!</p><h3>Step 2 — Access your hosting server folders</h3><p>As we explained above, a <em>hosting server </em>is just a simple computer phisically located somewhere in the world. You bought a space inside this computer, and as its owner you must be able to browse into your folders.</p><p>You can do so through some access credentials and the <strong>FTP </strong>which stands for File Transfer Protocol. As its name suggests, it is a way to not only browse the server, but also transfer files from your pc to the server and viceversa.</p><p>In order to access via FTP, you need a particular kind of sofware called <strong>FTP clients. </strong>There are many programs around, but in this tutorial I will use one of the most famous: <strong>Filezilla Client </strong>which is freely downloadable <a href="https://filezilla-project.org/download.php?ype=client">here</a>!</p><p>Once you installed the program you can open it and you will see an interface, divided into 2 parts as shown in the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2BB-BVvZ22Hq7bKVqURq5w.png" /></figure><p>As you see, the left side shows the files in our pc , while the right side is dedicated to the files on the hosting server. It is blank, because you still have to connect to the it.</p><p>In order to connect to your hosting server you will need 4pieces of information, provided by your service provider:</p><ul><li>the FTP <strong>host name</strong> (commonly ftp.johnnoe.com for www.johndoe.com )</li><li>the FTP <strong>user name</strong></li><li>the FTP <strong>password</strong></li><li>the <strong>PORT</strong> (usually 21)</li></ul><p>Insert this information in the upper left fields as shown in the picture and click the <em>Quickconnect </em>button to connect to your hosting server!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IxC62B3FKwj48hPCobLE5g.png" /></figure><p>Once you connect to your <em>hosting</em> the right side of the interface will finally show some content. The content you see is different for each service provider. What is sure, is that there will be a folder whose file will be exposed to the web. That is the <strong>public folder </strong>and there is where we will have to place our WordPress files.</p><p>In my case, the public folder is public_html (see pic below). This folder represents for me the root of my website. This means that, given my domain (marcolanci.it) if I place my WordPress files directly there, then you will see my website at www.marcolanci.it. Else, if I were to put my WordPress files in a folder named hello and then place this folder inside public_html , my WordPress website woud be reachable at www.marcolanci.it/hello.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bk2YVQfpW5IivpzeHcqc_Q.png" /><figcaption>On the left you can see my hosting server content and my public folder</figcaption></figure><p>Now, let’s stick with the initial idea: you have a <em>johndoe.com </em>domain and want your WordPress website to be reachable at www.johndoe.com . This is what you need to do: first of all, you need to identify which is the <strong>public folder </strong>on your <em>hosting server, </em>your provider will give you this information, and in some cases, it is also possible that when you access your FTP you are placed directly inside your public folder.</p><p>Once you found your folder, open it in the right side of Filezilla Client. On the left side, navigate into your files to the folder containing the wordpress files, the one we downloaded in step 1, so to have a situation like shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*feIOVv35AzFdEm1JaF66Ng.png" /></figure><p>At this point all you have to do is to select all the files on the left from wp-admin to xmlrpc.php and drag them into your public folder on the right! If you see some files on the right side, don’t worry about them.</p><p><strong><em>note:</em></strong><em> you can also drag the files directly from your computer folder to the right side of filezilla, it makes no difference.</em></p><p>At this point, you will notice that the tabs on the bottom left of Filezilla Client interface will start displaying some numbers. More precisely, the number on the <strong>Queued files </strong>tab on the left will constantly decrease while the number on the <strong>Successful transfers </strong>on the right will constantly grow. This means you are correctly transfering the WordPress files to your <em>hosting server</em>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*8J4252aCfKRjiqBqAddtvg.png" /></figure><p>The process may take a long time so don’t worry, just wait untill the <strong>Queued files </strong>tab reaches 0.</p><p>It is possible that during the transfer a popup like this may appear. Don’t worry: just select the <strong>overwrite </strong>option check the <em>Apply to current queue only.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WG9jaTIJNxewpqkwGkdaA.png" /><figcaption>A few pop ups like this may appear during the transfer.</figcaption></figure><p>If you see some number on the <strong>Failed transfer tab </strong>it is not a problem. Wait for the process to end. Right afterwords, click on the tab, select the files and right click on them. then select “<em>Reset and requeue all</em>”. If you still have failures, try to click and transfer them one by one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tbcelbleYP6JyjVKsIffUg.png" /><figcaption>There may be some failed transfers, click on the tab, select the files and right click on them to reset the queue.</figcaption></figure><p>If the queue does not restart automatically, just right click on the <em>Queued files </em>tab and select “<em>process queue”. </em>At the end of the process, you shall see all the files on the right side, and no numbers on both the <em>Queued files </em>and <em>Failed transfers</em> tabs, this means the WordPress website is ready to be installed and configured!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yO4tfC-RjQr-bTiclYHPbw.png" /><figcaption>There we go, no queued files nor failed transfer! Let’s go on!</figcaption></figure><h3><strong>Step 3 — Installation and configuration</strong></h3><p>Ok my friends, once the files are in the right place, we are ready to complete the installation! What you need to do is open your browser and go to the address where your files has been copied.</p><p>So if you have a johndoe.com domain and you placed the files directly inside your public directory, you just need to go to www.johndoe.com ; if you placed them into a foo directory inside your public directory, then you need to go on www.johndoe.com/foo .</p><p>Once you get to this address you will be immediately redirected to the wordpress configuration flow! As a first step, select your language:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZfnbUbUe_fW6u9pinkCgMA.png" /></figure><p>Once you selected the language, WordPress will tell you to ensure you have spe pieces of information: database name, username, password and host.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*K4qgUdG1AhY_bTkt7pyxkw.png" /></figure><p>You can get this information from your service provider. It is usually sent via e-mail when you bu the services but you can find it by accessing with your account to the control panel of your service provider or by contacting them for support. Once you have the information needed you can click on the <em>Let’s go </em>button and you will be shown the following form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNM34IlfKEqMjuBtruVYzA.png" /></figure><p>Insert the information you’ve got. If your provider did not specifiy any host, then leavelocalhost in the host field. As for the Table Prefix, you can leave it as it is ( wp_ ) if you only have one WordPress installation on your database.If you have more than one, then you can name t differently (i.e. wp_site2 ).</p><p>If your information is successful, you will see this message!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*0Lgh6YYjuVCjm4DVX6kMlQ.png" /></figure><p>Let’s click on the button and let WordPress make its magic. When it’s ready, you will be asked about some basic information about your new website and your account as administrator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M6j_t1VrDA9s-71pxmdOuA.png" /></figure><p>Once you filled the form, you will be redirected to the login screen, where you can access with your freshly created admin credentials and.. there you go!</p><h3>Congratulations!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ov1DcaSZGbgPkhLyQa3JEQ.png" /></figure><p>A complete new WordPress website is ready for you! You have now access to your admin panel and can start crafting your website as you like!</p><p>See? it wasn’t so hard after all! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84046db5ccd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fullstack CRUD application with Fastify, Mongoose and React Admin (Part 2)]]></title>
            <link>https://lancellotti-marco.medium.com/fullstack-crud-application-with-fastify-mongoose-and-react-admin-part-2-89cb48789405?source=rss-4e1214375ade------2</link>
            <guid isPermaLink="false">https://medium.com/p/89cb48789405</guid>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[fastify]]></category>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[react-admin]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Marco Lancellotti]]></dc:creator>
            <pubDate>Fri, 16 Oct 2020 17:16:30 GMT</pubDate>
            <atom:updated>2020-10-19T06:58:44.414Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fullstack CRUD application with Fastify, Mongoose and React Admin (Part 2— Frontend)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-tUzFitXdtu610zP4IKAQ.png" /></figure><p>Hey guys, this is the second part of my tutorial about <a href="https://www.fastify.io/"><strong>Fastify</strong> </a>and <a href="https://marmelab.com/react-admin/"><strong>React Admin</strong></a>. In this second part we are going to build the frontend of our CRUD todo list application with React admin and connect it to the Fastify backend we developend previously! If you missed part 1, you can find it <a href="https://medium.com/@lancellotti.marco/fullstack-crud-application-with-fastify-mongoose-and-react-admin-86d3e743dcdf">here</a>. If you want to skip reading and go straight to the code, you can find all the <strong>frontend source code </strong><a href="https://github.com/LanciWeb/react-admin-notes-frontend">here</a>, and the complete <strong>backend code </strong><a href="https://github.com/LanciWeb/fastify-notes-backend">here</a>!</p><h3>Small Recap</h3><p>So as a small recap for the previous part of the tutorial: we put together a Fastify app, connected it to our MongoDB and created a collection of <em>notes. </em>We also created a Note Model to be able to perform classical CRUD operations on our collection and set up the endpoints following REST conventions. Finally, we added a preHandler Hook that manipulates our responses, adding a <em>Content-Range</em> header that contains the name of our resource (<em>notes), </em>information about the pagination and the total number of notes in our database, as required by <a href="https://marmelab.com/react-admin/DataProviders.html#usage">React Admin documentation</a>. We will not have to worry about thiese headers on the frontend side since React admin is going to take care of them automatically. We are now ready to setup the frontend project so…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*xZ4oAnguSrXTlAFY_xO-hQ.gif" /></figure><h3>Project Setup</h3><p>Choose a location on your pc and open your terminal. This time aroud we don’t need to create a folder for the project since create-react-app will create it for us. Type the following in your terminal:</p><pre>npx create-react-app notes-client<br>cd notes-client<br>npm install react-admin @material-ui/core --save</pre><p>In doing so, we created a new folder called <em>notes-client </em>for our project and installed both <strong>React admin</strong> and <strong>Material-UI. </strong>This allows us to leave the styling/CSS part of the application aside from our concern, since React admin basic component have a basic styling based on the Material-UI library.</p><p>Before you go on, open your terminal and make sure everything compiles correctly by running npm start. If so, you should see your browser popping up with the classic React App logo spinning into your main page at localhost:3000.</p><h3>A little cleanup</h3><p>Using create-react-app is very handy when we want to rapidly initialize a React app, but brings with it some files which are useless for this project. Inside the <em>src</em> folder of the project, you can get rid of the following files: <em>App.css, App.test.js, logo.svg </em>and <em>setupTests.js.</em></p><p>Also, we will clean the <em>App.js </em>file so that our final result will be the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04370888ba56e0c4b3adee0b4df489d8/href">https://medium.com/media/04370888ba56e0c4b3adee0b4df489d8/href</a></iframe><h3>The Data Provider</h3><p>Before we actually start to use React admin and its component we have a very important step ahead. In order for React admin to perform its magic, we need to specify a <strong><em>dataProvider </em></strong>to be used whenever it needs to communicate with the APIs.</p><p>The <em>dataProvider </em>is but an object that <strong>must</strong> have the following methods:</p><pre>const dataProvider = {<br>    getList:    (resource, params) =&gt; Promise,<br>    getOne:     (resource, params) =&gt; Promise,<br>    getMany:    (resource, params) =&gt; Promise,<br>    getManyReference: (resource, params) =&gt; Promise,<br>    create:     (resource, params) =&gt; Promise,<br>    update:     (resource, params) =&gt; Promise,<br>    updateMany: (resource, params) =&gt; Promise,<br>    delete:     (resource, params) =&gt; Promise,<br>    deleteMany: (resource, params) =&gt; Promise,<br>}</pre><p>Quoting directly from the official documentation:</p><blockquote>the Data Provider’s job to turn these method calls into HTTP requests, and transform the HTTP responses to the data format expected by react-admin. In technical terms, a Data Provider is an <em>adapter</em> for an API.</blockquote><p>If you are lucky enough, you can find a ready-to-use dataProvider for your backend framework among the officially <a href="https://marmelab.com/react-admin/DataProviders.html#available-providers">Available Data Providers</a>. In that case you can just import the data provider in your project and pass it to the <em>Admin </em>component that will wrap the entire application (see later).</p><p>In our case, we wll have to face a small issue: React admin expects an id property as a key for the resources we want to manipulate, but on MongoDB, the key for documents is _id . Therefore, as explained in the <a href="https://marmelab.com/admin-on-rest/FAQ.html#can-i-have-custom-identifiers-primary-keys-for-my-resources">FAQs section</a> of the docs, we will have to define our own provider and remap the id property to our _id key.</p><p>Scrolling down the dataProvider documentation page, we can find a <a href="https://marmelab.com/react-admin/DataProviders.html#example-implementation"><strong>full example</strong></a> of dataProvider implementation, which needs just a few updates on our side in order to work fine with our database.</p><p>So this is what we will do: we will copy the entire implementation example, and just remap the keys of all methods we need to use in this fashion:</p><pre>return { ...json, id: json._id };</pre><p>Here is the final result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bb4fd3cee114e2586c19cb3319b157b/href">https://medium.com/media/0bb4fd3cee114e2586c19cb3319b157b/href</a></iframe><p><strong><em>Important Note: </em></strong><em>at the top of the file, we defined the </em>apiUrl <em>to </em><em>localhost:</em><strong><em>3000</em></strong><em>/api even though our backend app is running on port 5000. This is to prevent CORS problems and needs an extra step: inside your frontend </em><strong><em>package.js</em></strong><em> you need to add a “</em><strong><em>proxy</em></strong><em>” property as follows:</em></p><pre>&quot;proxy&quot;: &quot;http://localhost:5000&quot;</pre><h3>The Admin Component</h3><p>Okay my friends, with the dataProvider in place we are finally ready to get our feet wet with React admin components, so let’s begin.</p><p>As a first step, what we need to do is wrapping ouur whole application inside the <strong><em>Admin</em></strong><em> </em>component. The Admin component represents the whole backoffice of our application and it has just one mandatory prop: <em>dataProvider. </em>Let’s open again our <em>App.js</em> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3efa0061b7453b7e4678580e4b03e032/href">https://medium.com/media/3efa0061b7453b7e4678580e4b03e032/href</a></iframe><p>We imported our <em>dataProvider </em>and passed it as a prop to the <em>Admin </em>component. However, Admin alone cannot do much without some resource to work with…</p><h3>The Resource Components</h3><p>The Resource components are the core of React admin. Each of them represents a single resource model inside our backoffice, and will take care of showing the appropriate component for each of the operation we want to perform on the resources they stand for. We could pass as many Resource components as we want as children of Admin, but in our case, we only have our resource to work with: our notes. Let’s edit <em>App.js </em>one more time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/374f572b25638a30234e4d7dd220a10a/href">https://medium.com/media/374f572b25638a30234e4d7dd220a10a/href</a></iframe><p>We imported the <em>Resource </em>component and pass it 3 important props:</p><ul><li><strong>name</strong> defines the name of the resource that will displayed in many places throughout our frontend backoffice panel</li><li><strong>list </strong>specifies a component to show when we need the list of the resource, usually a table.</li><li><strong>edit </strong>specifies the component to show when we edit a resource, that is, a form.</li><li><strong>create: </strong>specifies the component to use when we create a new resource, in other words, a creation form.</li></ul><p>In the file above, we are importing and assigning a few component files that do not exist yet, so let’s create them now and we will work on them one by one right after! Inside your project root folder open the terminal, create a <em>component </em>folder and the three files: <em>NotesList.js, NotesEdit.js, NotesCreate.js</em></p><pre>mkdir src/components<br>touch src/components/NotesList.js<br>touch src/components/NotesEdit.js<br>touch src/components/NotesCreate.js</pre><h3>Displaying the list of notes</h3><p>To display the list of all our notes, we need to work on the component passed to the <em>list </em>prop of our <em>Resource</em>: <em>NotesList.js</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e16694f6c1666e14fad5131c015e6473/href">https://medium.com/media/e16694f6c1666e14fad5131c015e6473/href</a></iframe><p>Lot of stuff here, but really easy after all! As a first step, we imported a bunch of components from React Admin. All of them feature pre-built functionalities that will build our table for the list in a blink of an eye.</p><p>First things first: the <em>List </em>component is what we use when we want to set up a list page. We spread the props with the information coming from the Resource and Admin parent components, that will make List aware of which resource we are listing and which methods to use when contacting the APIs.</p><p>The <em>Datagrid</em> component is the acual table in which we can specify the columns we want to show. Each children of Datagrid will be displayed as a column. We provided 2 <em>TextField</em> components; one to display the id column and another for the text column. Note that the <em>source </em>prop of these components must match the proprties of the resource, that is, the properties we defined inside our <em>NoteSchema, </em>with the exception of the _id which has been mapped in the data provider as id .</p><p>After that, we also provided the <em>EditButton </em>and the <em>DeleteButton </em>so to have the relative actions on each row. What is important to note is the <em>basePath </em>prop inside the button components: here is where the magic of React Admin reveals itself. The path we specify will be joined to the <em>baseUri </em>defined inside the <em>dataProvider, </em>and React Admin will automatically add the id of the instance we want to delete or edit, as expected in the REST conventions!</p><p>While the <em>DeleteButton </em>will now work out of the box, we need a further step for the <em>EditButton: </em>define the <em>NotesEdit</em> component to show when the button is clicked.</p><h3>Edit a note</h3><p>The <em>EditButton</em> defined in the <em>NotesList </em>component<em> </em>will redirect the view to the component that we provided in the <em>edit </em>prop of the <em>Resource</em> component: <em>NotesEdit.js. </em>Let’s put inside the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e4b4578833ad2f2b42c0b5bf4267050/href">https://medium.com/media/2e4b4578833ad2f2b42c0b5bf4267050/href</a></iframe><p>This time around, we want to create a page to edit a resource so the <em>Edit</em> component is what suits us. We pass inside it the spread props, and then we pass a <em>SimpleForm</em> component as its child, since we definetly need a form to edit a note!</p><p>Inside <em>SimpleForm</em> we can list a number of components to render the different fields we want to show. Again, the <em>source </em>prop of these components must match the resource proprties so we have one <em>TextInput </em>component for the <em>id</em> and one for the actual <em>text</em> of the note. We also marked the <em>id</em> field as disabled since we don’t want to let users to edit the id of our notes; and the <em>text </em>field<em> </em>as required because a note without text… well, is not a note.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*UlhH1JXCgRff-2hJ9AF4dg.png" /><figcaption>Final look of the edit form</figcaption></figure><h3>Creating a new note</h3><p>Our last step is to define the <em>NotesCreate.js </em>file that is supposed to show a component to handle the creation of new Notes.</p><p>By clicking on the plus icon at the top of the Notes view, this component will be rendered. Let’s instruct React admin on what to show within it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bdd11764398e1189ab6f36074c85517/href">https://medium.com/media/5bdd11764398e1189ab6f36074c85517/href</a></iframe><p>This is definitely the easiest component and it is very similar to the <em>NotesEdit</em>. The only differences are the use of the <em>Create</em> component instead of the <em>Edit </em>one, and the obvious absence of the <em>id </em>field, since the id will be automatically assigned to the new notes by our MongoDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*xNnCdQl77nyNI4m5zdzCyw.png" /><figcaption>Final look of the Creation Form</figcaption></figure><h3>TA-DAH!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*9WAwwg8f0YKFMyEbHVFaPg.png" /><figcaption>Final result, note the create button and the CSV export on the top right side, the left side of the app is where all our resources will be listed</figcaption></figure><p>There we go my friends! 5 files in total (included the copy-pasted data provider), and this is what we get, perfectly working and already styled. Would you believe it was so easy? And, you also got <strong>CSV Download<em> </em></strong>out of the box!</p><p>I’ll leave the next steps to you so to play around with this application: I invite you to <strong>complete the app for multiple actions</strong> such as multiple cancellation (hint: you need to edit the <em>dataProvider.js </em>file), try to <strong>add filters</strong>, <strong>sorting rules</strong> , <strong>restyle</strong> the appearence and if you want, <strong>try to add other resources</strong>!</p><p>I really hope you enjoyed this tutorial and hope you also got in touch with some tech you didn’t know. See you in the next tutorial!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89cb48789405" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fullstack CRUD Application With Fastify, Mongoose and React Admin (Part 1 — Backend)]]></title>
            <link>https://medium.com/swlh/fullstack-crud-application-with-fastify-mongoose-and-react-admin-86d3e743dcdf?source=rss-4e1214375ade------2</link>
            <guid isPermaLink="false">https://medium.com/p/86d3e743dcdf</guid>
            <category><![CDATA[react-admin]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[fastify]]></category>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[mongoose]]></category>
            <dc:creator><![CDATA[Marco Lancellotti]]></dc:creator>
            <pubDate>Fri, 16 Oct 2020 17:15:23 GMT</pubDate>
            <atom:updated>2020-11-26T11:03:50.234Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fullstack CRUD Application With Fastify, Mongoose and React Admin (Part 1 — Backend)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*UbSLlfidhcBMzqYjjvl_eg.png" /></figure><p>Have you ever realized how repetitive and somehow boring it is to make up the frontend for backoffice CRUD operations over and over in all your projects? Well, a few days ago I randomly ran across this interesting package named <a href="https://marmelab.com/react-admin/"><strong>React Admin</strong></a> by marblelab, which promises to definitely boost the whole process on the frontend side! I therefore decided to give it a try and make a small, fullstack CRUD application, using <a href="https://www.fastify.io/"><strong>Fastify</strong></a> and <a href="https://www.mongodb.com/"><strong>MongoDB</strong></a><strong> </strong>/ <a href="https://mongoosejs.com/"><strong>Mongoose</strong></a> for my backend stack.</p><p>In this tutorial, we are going to build a todo list-like application in 2 parts, in the first one, we will build the backend with fastify and set up the endpoints to handle all the CRUD operations over our notes. In the <a href="https://medium.com/@lancellotti.marco/fullstack-crud-application-with-fastify-mongoose-and-react-admin-part-2-89cb48789405">second one</a>, we will implement React Admin to build the frontend facade of our app. You can find the complete source code for the <strong>backend</strong> <a href="https://github.com/LanciWeb/fastify-notes-backend">here,</a> and the complete source code for the <strong>frontend</strong> <a href="https://github.com/LanciWeb/react-admin-notes-frontend">here</a>!</p><h3>What you need to know to follow</h3><p>In order to follow this tutorial and get the most out of it, you should have a basic understanding of REST principles and a (very) basic knowledge of React, MongoDB and FAstify or some other Node.js framework such as Express.js. I will also use ES6 syntax, so the knowledge of concepts like destructuring and arrow functions are also given for granted. However, I will try my best to explain each part of the code and you can always comment below if you have any doubt. In general, the concepts shown in this project are not super advanced so you may give it a try even if you don’t feel super confident in one of the technologies listed above. Enough chit-chat now..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*dCqKWoZsq7yHzzwKtz9HVQ.gif" /></figure><h3>Project Setup</h3><p>Before we begin, make sure to have globally installed <a href="https://nodejs.org/en/"><strong>Node.js</strong></a> on your machine, this is crucial to import all our dependencies and set up both the backend and the frontend projects. Also, I will use a local instance of <a href="https://www.mongodb.com/"><strong>MongoDB</strong></a><strong> </strong>for the database, but you can also use a free cluster hosted on <a href="https://www.mongodb.com/cloud/atlas/"><strong>MongoDB Atlas</strong></a><strong>.</strong></p><p>So, in order to setup the backend side, let’s create a new folder for the project, install our dependencies and set up the structure. In your terminal:</p><pre>mkdir notes-server<br>cd notes-server<br>npm init -y<br>npm install fastify mongoose --save<br>mkdir src<br>touch src/index.js</pre><p>So, line by line: (1) we created a <em>notes-backend</em> folder, (2) entered the folder, (3) initialized a Node project, (4) installed Fastify and Mongoose as dependencies, (5)created a new <em>src</em> folder with (6) an <em>index.js</em> file which will be the root for our application.</p><p><strong>Connection to MongoDB and app running</strong></p><p>Now, let’s get the Fastify app running together with the MongoDB connection. So, in the <em>index.js</em> file we just created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85d4e03fe0a9fadcc075211434ee5f70/href">https://medium.com/media/85d4e03fe0a9fadcc075211434ee5f70/href</a></iframe><p>We imported fastify and mongoose and initialized the app by calling the fastify function. The <em>mongoose.connect </em>function let us specify a <em>mongoUri</em> to connect our database to the app, so I put my local port 27017, where my MongoDB instance is running(if you are using a cluster in MongoDB Atlas, you can find your mongoUri in the connection section, but remember to list your ip address into the whitelist of allowed connections.). At the veryend of the mongoUri, you can specify the name of the db for the project. In my case, I called it <em>notes_db. </em>You can call it whatever you want, if a database with that name does not exist in your MongoDB instance, Mongoose will create it for you!</p><p>We then handle the root route of our application with the <em>app.get </em>function. This handles a GET request on the root (‘/’) address of our app. When we want to handle a route on a Fastify App, we need to provide a function with the <em>request </em>and <em>reply </em>parameters. As you may guess, the former contains all the information related to the request while the latter is meant for us to return a proper reply to the endpoint. For now, we just <em>reply.send() </em>a simple string.</p><p>Finally, the the <em>app.listen </em>function sets our application listening to the port 5000. Let’s now put it to the test. To do so, first open the <em>package.json </em>file in the root of our applicaion and add the following “start” script inside the <em>scripts </em>object:</p><pre>&quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node src/index.js&quot;,<br> },</pre><p>If you now run npm start from your terminal you should see a message saying “Server running on http://127.0.0.1:5000”. Open your browser at <a href="http://localhost:5000/"><em>http://localhost:5000</em></a><em> </em>and you should see our “Hello world!” string, meaning our app is running successfully!</p><h3>Defining the Note Schema</h3><p>At this point, we want to have a <em>notes </em>collection inside our database, and we also need to define the properties that a note document should have. We do so by creating a Note Model and providing a Model Schema, that is, an object with all the specification for a typical note document. Let’s create a new folder and file inside our project; in your project folder terminal:</p><pre>mkdir src/models<br>touch src/models/Note.js</pre><p>Let’s edit this new file as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea544d50811f4aad17f8873c1e264371/href">https://medium.com/media/ea544d50811f4aad17f8873c1e264371/href</a></iframe><p>Basically we are using Mongoose’s Schema object to explicitely declare to our MongoDB that our notes will have a mandatory propery called text, which is, naturally, a string. We are then defining it as a model with the <em>mongoose.model </em>function. The first parameter is a string that will be used by mongo to define the name of the collection: given a “note” model, we will find a “notes” collection in our database after our very first operation with a Note. Finally, we export the newly created Note model and make it available throughout the application.</p><h3>Implementing REST APIs</h3><p>It is now time to define our api routes for the CRUD operations we will perform on our notes.We will approach our APIs following the well-known and vastely-established REST conventions. For those of you who are not familiar with REST, it is architectural style that defines a set of constraints to help developers structuring APIs in a clear and reliable standard.</p><figure><img alt="Rest CRUD conventions" src="https://cdn-images-1.medium.com/max/1024/1*hBLAlNr-co6BlZhCTxDyVg.jpeg" /></figure><p>In the picture above, you can see how endpoints should be structured for all the operations (Create, Read, Update and Delete) and what each of them is supposed to return. We will follow these guidelines for our routes, by splitting them into 2 different files, one to define the routes, and another to define the route handlers, that is, the functions that will take care of performing the actual operations and return the proper response from the endpoints.</p><h3>Defining API Routes (Endpoints)</h3><p>Inside of our <em>src </em>folder, we will now create a new <em>routes </em>folder, with a <em>noteRoutes.js</em> file in it. So in the terminal, let’s type this:</p><pre>mkdir src/routes<br>touch src/routes/noteRoutes.js</pre><p>Within this file, we will export a function whose only parameter will be the entire fastify app, and whose return value is a list of routes to be added to the app itself. For each route, we specify the HTTP verb to be handled, a url, and, finally a handler function, that we will define in a second step.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92b417a4a1da372b6ba451d5b6f608a4/href">https://medium.com/media/92b417a4a1da372b6ba451d5b6f608a4/href</a></iframe><p>We can now perform:</p><ul><li>A <strong>POST </strong>call to api/notes to <em>Create a note</em></li><li>A <strong>GET </strong>call to api/notes to <em>get the List of all of our notes</em></li><li>A <strong>GET</strong> call to /api/notes:id to <em>retreive a single note</em></li><li>A <strong>PUT</strong> call to /api/notes:id to <em>Update a given note</em></li><li>A <strong>DELETE </strong>call to /api/notes:id<em> </em>to <em>Delete a specific note</em></li></ul><p>The :id is obvously a placeholder for the id of our document, and we will be able to access it inside the <em>request</em> params of our route handler function as request.params.id . (We’ll take care of the handlers in the next section).</p><p>As shown in the file above, we need to have access to the app object in order to call the route handlers on it, therefore, we must import this file into our <em>index.js </em>and call it with the fastify app as its parameter:</p><pre>//index. js</pre><pre>const app = fastify();<br>const fastify = require(&#39;fastify&#39;);<br>const mongoose = require(&#39;mongoose&#39;);<br><strong>const noteRoutes = require(&#39;./routes/noteRoutes&#39;);</strong></pre><pre>try {<br>  mongoose.connect(&#39;mongodb://localhost:27017/notes_db&#39;);<br>} catch (e) {<br>  console.error(e);<br>}</pre><pre><strong>noteRoutes(app);</strong></pre><pre>app.listen(5000, (err, address) =&gt; {<br>  if (err) {<br>    console.error(err);<br>    process.exit(1);<br>  }<br>  console.log(`Server running on ${address}`);<br>});</pre><h3>Moving API Route Handlers (Controller)</h3><p>Now that we have our routes, we need to define our handlers for each of the routes. For the sake of cleaninless, we will move our handler functions in an external file, where we will define the logics and from which we will export and assign them to their respective routes. We refer at such files as <strong>controllers</strong>. So, as a first step, let’s create a <em>controllers </em>folder in our <em>src </em>and inside of it, let’s add a new file named <em>notesController.js. </em>As usual, inside the project root folder let’s open our terminal and type:</p><pre>mkdir src/controllers<br>touch src/controllers/notesController.js</pre><p>Let’s now work on the newly created controller, <em>notesController.js</em> :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/617840b8cebf8e8d0f5f3d3e056a9af0/href">https://medium.com/media/617840b8cebf8e8d0f5f3d3e056a9af0/href</a></iframe><p>As a first thing, we are importing our Note model, which will be used to perform operations against our database thanks to Mongoose methods. We have then defined a function for each of the operation, and mark them as <strong>asyncronous</strong>, since our database will need some amount of time to complete its processing, and we will need to wait for it.</p><p>Let’s leave the actual implementation of the handlers for later and let’s just connect our route file with these newly decleared functions. Inside <em>notesRoutes.js, </em>we import the controller and assign the respective functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/741a560b0b6c158ef684350a58c8617e/href">https://medium.com/media/741a560b0b6c158ef684350a58c8617e/href</a></iframe><h3>Defining Route HandlerFunctions</h3><p>Let’s now focus on each of our handler functions inside <em>noteControllers.js.</em></p><h4>Create a note</h4><p>In order to create a note the first thing we need to do is to extract the information about the new note we are supposed to create from the body of the request. After that, we will use Mongoose’s create method, which will create a new document and return it back to us. We are then ready to set the proper HTTP status (201) and to return our brand new note, as requested by REST conventions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecc6e84cf84561a99a7967a38a5337b5/href">https://medium.com/media/ecc6e84cf84561a99a7967a38a5337b5/href</a></iframe><h4>Get the list of the notes</h4><p>This is probably the easisest one, we will receive our GET call and we will use the <em>find</em> method on our Note model, providing an empty object as a parameter. The first parameter could contain a MongoDB query object to specify some critera about which notes to get. Thus, the empty object will return all of the notes in the collection. We can then send them back in our response:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcb432ac580f3da2d805180f7d19fb7d/href">https://medium.com/media/fcb432ac580f3da2d805180f7d19fb7d/href</a></iframe><h4>Get a single note</h4><p>This time around our first step will be to get the id of the note we want to retreive from the request url. When we define plaeholders inside the route url,(such as we did with the <em>:id </em>in our routes) they will be available for us inside the <em>request.param</em>s object. Once we get the id we are finally able to invoke the <em>findById </em>metod on the Note model and retreive the desired note by passing the id as the only parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/342dea67674fcb2cc666ca5c59ed9b51/href">https://medium.com/media/342dea67674fcb2cc666ca5c59ed9b51/href</a></iframe><h4>Update a note</h4><p>The update requires us to take both the body of the request <strong>and </strong>the id from the url. The body, will contain the note properties that need to be modified, while the id will be necessary to identify which note to update. With these two pieces of information at our disposal, we can use the <em>findByIdAndUpdate</em> method, passing the id of the note as a first argument, and the data coming from the body as the second one.</p><p>Unlike the <em>create, find, </em>and <em>findById </em>methods, <em>findByIdAndUpdate </em>does not return the updated object, forcing us to fetch the database again in order to send the freshly modified note back as a response.</p><p><strong>Note: </strong><em>we return the response inside the data property of an object because React Admin requires it in its documentation.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8b84961c2b1563f71ce04d709c248c0/href">https://medium.com/media/a8b84961c2b1563f71ce04d709c248c0/href</a></iframe><h4><strong>Delete a Note</strong></h4><p>Our last handler will take care of the cancellation of a note. No body required here, we just need the get the id from the url as usual and pass it to the <em>findByIdAndDelete </em>method<em>. </em>As you would expect, this method cannot return from the database an object who has just been deleted, so in this case, we will have to retreive the note <strong>before</strong> deleting it. We can do it similarly to what we did earlier in the “get single note” handler:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7a7b81f10f1370290962d03d012ae64/href">https://medium.com/media/d7a7b81f10f1370290962d03d012ae64/href</a></iframe><p>There we go! We have completed or Controller file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba824a7bcd94bcc96d83c14e196ce4ec/href">https://medium.com/media/ba824a7bcd94bcc96d83c14e196ce4ec/href</a></iframe><h3>One last step</h3><p>We successfully managed to set up all our API endpoints, but we haven’t finished yet. In order to make React Admin and our backend working properly together, we need to make sure to include a particular header every time our endpoints send back a response.</p><h4>The Content-Range header</h4><p>According to <a href="https://marmelab.com/react-admin/DataProviders.html#usage">React Admin offical docs</a>, the package relies on the <em>Content-Range </em>header to properly manage and display the pagination of its tables.This is what React admin expects to find in the header:</p><pre>Content-Range: posts 0-24/319</pre><p>The value represents the name of the collection, followed by the number of items displayed and the total number of documents inside the collection.</p><h4>Fastify preHandler hook</h4><p>So the question is: how do we do that? And the answer is: with a hook!</p><p><strong>Fastify hooks</strong>, are functions we can use to set some custom code in given moments of the workflow of our application. There are many type of hooks that can be invoked with fastify’s <em>addHook </em>function. Let’s define a hook inside a new folder! In the terminal:</p><pre>mkdir src/hooks<br>touch src/hooks/contentRangeHook.js</pre><p>Before working on its logic, we import this file inside <em>index.js, </em>just before our routes:</p><pre>//index. js</pre><pre>const app = fastify();<br>const fastify = require(&#39;fastify&#39;);<br>const mongoose = require(&#39;mongoose&#39;);<br>const noteRoutes = require(&#39;./routes/noteRoutes&#39;);<br><strong>const contentRangeHook = require(&#39;./hooks/contentRangeHook&#39;);</strong></pre><pre>try {<br>  mongoose.connect(&#39;mongodb://localhost:27017/notes_db&#39;);<br>} catch (e) {<br>  console.error(e);<br>}</pre><pre><strong>app.addHook(&#39;preHandler&#39;, contentRangeHook);</strong><br>noteRoutes(app);</pre><pre>app.listen(5000, (err, address) =&gt; {<br>  if (err) {<br>    console.error(err);<br>    process.exit(1);<br>  }<br>  console.log(`Server running on ${address}`);<br>});</pre><p>As you see in the highlighted line above, addHook recevies the type of hook as a string in its first parameter (the complete list of the hooks is <a href="https://www.fastify.io/docs/latest/Hooks/">here</a>), and the hook function itself, in the second.</p><p>In order to manipulate the <em>reply </em>object of our endpoints, we need to use the <strong>preHandler </strong>hook, which receives as parameters both the <em>request </em>and the <em>reply</em> objects, plus the <em>next</em> function, that we are supposed to call at the end, letting fastify know that we finished our logics and natural flow of the app can go on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39ea65a6f83ecc1d470535f47c1ecd03/href">https://medium.com/media/39ea65a6f83ecc1d470535f47c1ecd03/href</a></iframe><p>In order to provide the proper information to React Admin inside our Content-Range header, we want to at least get the real number of documents inside of our collection. To do so, we can use Mongoose’s <em>count </em>method. As we did with the <em>find </em>method before, we provide an empty object as a query, without specifying any filter criteria (it’s a test app after all!).</p><p>Once we obtained this information, we can prepare the Content-Range header string: we specified <em>notes </em>as item names, set the pagination and interpolated the total number of documents at the end of the string.</p><p>We are now ready to use the <em>reply.header</em> setter method, to specify the name of the header and its content. Accomplished the hook task, we can call <em>next()</em>!</p><p><strong>Note: </strong><em>the pagination was arbitrarily set to a maximum of 10 notes for no particular reason.</em></p><h3>Congrats!</h3><p>That’s it for the first part! We put our backend in place, set up our routes, manipulated our header to work fine with React Admin and we are now ready to build the frontend in <a href="https://medium.com/@lancellotti.marco/fullstack-crud-application-with-fastify-mongoose-and-react-admin-part-2-89cb48789405"><strong>part 2</strong></a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86d3e743dcdf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/fullstack-crud-application-with-fastify-mongoose-and-react-admin-86d3e743dcdf">Fullstack CRUD Application With Fastify, Mongoose and React Admin (Part 1 — Backend)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>