<?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 Chime Princewill on Medium]]></title>
        <description><![CDATA[Stories by Chime Princewill on Medium]]></description>
        <link>https://medium.com/@princewillchime43?source=rss-ca30ca69cc7e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*3C5pZHfv_Fuu4SaXZe2SMQ.jpeg</url>
            <title>Stories by Chime Princewill on Medium</title>
            <link>https://medium.com/@princewillchime43?source=rss-ca30ca69cc7e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 08:51:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@princewillchime43/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[Apollo Client’s Hidden Superpower: Unifying REST, GraphQL, and WebSockets.]]></title>
            <link>https://princewillchime43.medium.com/apollo-clients-hidden-superpower-unifying-rest-graphql-and-websockets-8100e5d5502c?source=rss-ca30ca69cc7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8100e5d5502c</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[apollo-client]]></category>
            <dc:creator><![CDATA[Chime Princewill]]></dc:creator>
            <pubDate>Thu, 01 Jan 2026 04:15:09 GMT</pubDate>
            <atom:updated>2026-01-01T04:15:09.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gXyr2bcGYVIXLm7n" /><figcaption>Photo by <a href="https://unsplash.com/@lorencutler?utm_source=medium&amp;utm_medium=referral">Loren Cutler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Introduction<br></strong>As a frontend developer who uses libraries like Apollo Client to make requests to a GraphQL server/API, you may want to access data from a third-party API, which happens to be a RESTful API, and handle Apollo subscriptions.</p><p>If you are a senior/mid-level developer who wants to access a third-party API while working on an Apollo Client setup and integration of GraphQL Apollo subscription, you will love to stick around because this article is for you.</p><p><strong>Things To Learn</strong><br>In this article, I will guide you on how I handle the following:</p><ul><li>React set up with Apollo Client</li><li>Redux toolkit setup and usage</li><li>Custom UseQuery Setup</li><li>Good Error Handling in Apollo Client</li><li>Factoring of RESTful API within Apollo Client setup</li><li>Multiple Router Links</li><li>Best practices of React.js and more</li></ul><p><strong>Prerequisite</strong></p><ul><li>Know Javascript</li><li>Know React.js</li><li>Install NPM/Node</li><li>Know Typescript</li></ul><p><strong>Setup Environment<br></strong>To create a new React project, use the following<a href="https://create-react-app.dev/docs/getting-started/"> <strong><em>link</em></strong></a>, and name it rest_api_request_in_apollo_client. In your terminal, navigate to the desktop folder and install the following as shown below:</p><pre>npm create vite@latest . -- --template react-ts<br><br>npm install @apollo/client @apollo/client-rest graphql @reduxjs/toolkit react-redux axios<br><br>npm install @apollo/client apollo-link-rest graphql @reduxjs/toolkit react-redux axios graphql-anywhere qs</pre><p><strong>Setup Store<br></strong>To learn about the Redux Toolkit store, use the following <a href="https://medium.com/dev-genius/react-state-management-an-approach-you-missed-adabdf077eb8">link</a>.</p><p><strong>Set up Apollo Provider<br></strong>In the apolloClient.ts, add the following snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*OLkTWvRrLJPRD2oB6XqxJw.png" /><figcaption>rest router snipper</figcaption></figure><p>In the snippet above, I define the REST router link that will handle the REST API, ensuring it works well with the Apollo client useQuery. The restLink function is used to pass the necessary arguments, such as the uri, the header, and the responseTransformer, which handles the formatting of the returned data to suit the structure of the Apollo Query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*fePMv9O8K3XyXOZuPlOOiw.png" /><figcaption>graphQL link router snippet</figcaption></figure><p>In the snippet above, graphQLLink is creating an HttpLink instance that will be used as a link in the Apollo Client configuration. It specifies the URI for the GraphQL endpoint using the value from import.meta.env.VITE_PUBLIC_DB_URL! and sets the credentials option to “include”; the include is used to allow the cookie to be sent along with the request.</p><p>To make this setup work, I will have to conditionally use the router links above in the split method of the Apollo Library, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*EgZ3GVuK-5BOsmAgqRrsPg.png" /><figcaption>config the rest and graphql routers</figcaption></figure><p>The snippet above is simply using a conditional method to use either the restLink or graphQLLink. Let’s now use the ApolloLink to establish a connection of the router Links and set up the cache and default options accordingly, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*JBSdMbzr0NLhCOKsA2IsGg.png" /><figcaption>Apollo client set up</figcaption></figure><p>In the snippet above, I used the from method of the apolloLink to merge the router links and the error that would be used in the application. Let’s define the error link and handle the way errors are displayed accordingly in the snippet below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*P2Xcr0j8T2i5_9Kg-Ecd8g.png" /><figcaption>error configuration</figcaption></figure><p>When handling GraphQL errors, I love creating a central setup for the mutation errors and its server errors too. In the snippet above, I made a check to monitor when the GraphQL error operation is a mutation and when it is a server error in mutation operation too, and if so, I will loop through the error.errors to print the error message or pass it into a custom message handler.</p><p>The setup allows me not to handle mutation errors within the code, except when I want to handle other things when the requests fail.</p><p><strong>Query Restful API<br></strong>Now that I am done setting up, let’s head to the queries.ts file to build the query for the request</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*lZHCHSvwUoDKWDpQH8dWsw.png" /><figcaption>search book query</figcaption></figure><p>The snippet above is a regular GraphQL query except for the “@rest”, which is a directive that is provided by the Apollo client to make a RESTful API call within the GraphQL query. When a request a made, it gets all the returned data as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*yTP-MTqhkt6hYKccydqb9A.png" /><figcaption>books covers</figcaption></figure><p><strong>Query Apollo API</strong></p><p>Let’s go into the queries.ts and add the query for the Apollo API as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*X_aj_MQWaOngPVaev43DAg.png" /><figcaption>Apollo Query</figcaption></figure><p>This query is for all characters, and it also gives room to search by name and gender. Moreso, it handles pagination as well. Key things to note: for the rest, I used a directive “@rest”, but the Apollo query does not need any directives.</p><p><strong>Set Up For an Apollo Subscription<br></strong>To add the Apollo subscription setup, I will have to adjust the split setup above as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*gv17_oDa9GjsZkk7jHQrVA.png" /><figcaption>web socket links</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*N7tckvf5uYc-NEghEmtdgw.png" /><figcaption>Apollo Subscription</figcaption></figure><p>I am used to defining the subscription setup separately, so I confirmed that the operation is subscription, and it uses the wsLink; otherwise, it will run the httpOrRestLink split above and use the links accordingly.</p><p><strong>Advance Setup<br></strong>If you follow closely, you would notice that the split method I used in the above has been depreciated, but it still works for lower versions of React. However, there are cases I would want to ignore the directive “@rest” and override the split method for the router links. For that, I would do the following, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNPzeI5mVNiajCtv5cVJGw.png" /><figcaption>restLink refactoring</figcaption></figure><p>Let’s add the axios used for the request as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*sqwuWlkogVow4eBKTOE5jA.png" /><figcaption>axios call for the restful api</figcaption></figure><p><strong>Conclusion<br></strong>Finally, I was able to establish multiple router link connections in my Apollo client setup, integrated an Apollo subscription and effectively queried a RESTful API within an Apollo query.</p><p>From now on, I hope I have impacted you, so have fun while writing your code with best practices as a PRO</p><p>If this article was helpful to you, kindly like, comment, share and follow me on my <a href="https://www.linkedin.com/in/chime-princewill-3a2b1b192/">LinkedIn</a> and <a href="https://princewillchime43.medium.com/">Medium</a> to see more of my articles. Click the following link to access the <a href="https://github.com/chibuike07/rest_api_in_apollo_client">source code</a>, and don’t forget to give it a star.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8100e5d5502c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mongoose Populate: the query method that will amaze you.]]></title>
            <link>https://blog.devgenius.io/mongoose-populate-the-query-method-that-will-amaze-you-6bd0e6e60350?source=rss-ca30ca69cc7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bd0e6e60350</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[remote-work]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Chime Princewill]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 18:51:55 GMT</pubDate>
            <atom:updated>2024-06-04T06:29:15.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_M3-V7oRUC5JgNu5" /><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_source=medium&amp;utm_medium=referral">Christopher Gower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>When writing a server code, it is of the essence to have a good schema structure for better scalability and efficiency. With Mongoose Populate, you will be assured of mutual access across schemas/collections.</p><p>Have you imagined creating different schemas that should have a relationship with each other? Have you thought of reducing the making of unnecessary queries in your web applications? Please welcome this article.</p><p>I have a similar article that you may love to check out on <a href="https://medium.com/faun/mongoose-aggregation-in-nodejs-the-query-master-5e2ad3a0d1da">Mongoose Aggregation</a></p><h3>What is Mongoose Populate</h3><p>Simply put, it is a method that brings the children close to their mothers and creates a path for free access from the mother to any of her offspring. If this rings a bell let’s dive into it.</p><h3>Things To Learn</h3><p>In this article, I will show you how I handle the following:</p><ul><li>Schema referencing</li><li>Query Linked schema</li><li>Use populate to specify the returned values of the referenced schema</li><li>Conditional query using populate</li><li>Populate Nested Document</li><li>Inclusion and Exclusion of the populated schema values</li><li>Populate multiple sub-documents</li><li>Good Schema Structure</li><li>Best code practices</li></ul><h3>Prerequisite</h3><ul><li>Know Javascript</li><li>Know Nodejs/ExpressJs</li><li>Install MongoDB compass</li><li>Install Node/Npm</li></ul><h3>Folder Structure</h3><p>let’s navigate to the desktop directory through the terminal and run the following commands</p><pre>mkdir mongoose-populate<br>cd mongoose-populate<br>yarn init -y<br>mkdir src<br>cd src<br>mkdir model services routes<br>touch server.js<br>touch app.js</pre><h3>Environment</h3><p>To set up your server, click the following <a href="https://medium.com/dev-genius/mongoose-discriminator-an-easy-way-to-inherit-schema-properties-6c6e89c3795">link</a></p><h3>Connect to the MongoDB database</h3><p>To connect our application to the database, add the following code snippet to app.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*m0iRe0N-4DOo3tAikshj3A.png" /><figcaption>app.js</figcaption></figure><p>I created an instance of <a href="https://expressjs.com/en/starter/installing.html">express</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">cors</a>. The app.js will also be holding all the routers.</p><p>Let’s go into the server.js and add the following code snippet below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*toqxXTItNoxpvfiN5V1iww.png" /><figcaption>server.js</figcaption></figure><h3>Schema Design</h3><p>Let’s go into the model directory, create a new file named user.js, and add the following to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*qx6REFfWyX1yWmtoB5Ck8g.png" /><figcaption>user schema</figcaption></figure><p>I created a schema for the users, defined their types, validated the properties using the required field, and removed extra padding using the trim field.</p><h3>Schema Referencing</h3><p>Notice how the user job property type was different, it was set to an objectId and has the ref property which links another schema called jobs.</p><p>It enables the User schema to have access to the schema that is set as the value of the ref.</p><p>Now, let’s create a new file named jobs.js, where I will be defining the jobs schema as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*eyEsF_Qau2MLuXSxHF52eg.png" /><figcaption>jobs schema</figcaption></figure><p>Just like the User schema the properties are validated. and trimmed.</p><h3>Create User Services</h3><p>Let’s go into the services directory, create a file named user.js, and add the code snippet as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*_JryVln3Fm1aDA9R30ISyw.png" /><figcaption>user services</figcaption></figure><p>The userServices is an object that will be holding all the user middleware. The addUser is a middleware that will handle the adding of users, inside it, the request body was destructured, and a check was made to verify that the user does not exist before creating an instance of the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*2vVxFa3IKrUa_joRqBfSlA.png" /><figcaption>create an instance of user and jobs</figcaption></figure><p>After making the earlier check, the trycatch method is used to successfully create an instance of a job and user, catch any validation error, and delete the created job if something goes wrong while trying to save either the job or user. To have a save referencing, a unique identifier of the newly created job instance is added to the jobs array.</p><h3>Populate The User Jobs Schema</h3><p>Inside the userServices variable, let’s add the following code snippet into it as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*sYe-TU-qkJUCMiT2BopvaQ.png" /><figcaption>get a single user with their jobs</figcaption></figure><p>I set the query variable to be more flexible, so a user can be gotten using any of its properties — name, _id, and so on. The populate method was used to get all the jobs for the specified user and return them to the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*SguQnYm8tTE7nJySRMSV0Q.png" /><figcaption>output</figcaption></figure><p>The code snippet above returns the user object with the user jobs and not having the jobs as an objectId that is inside of an array</p><h3>Using Populate To Specify The Returned Referenced Values</h3><p>Furthermore, the populate method allows the specification of the returned value as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*cM6fMVLm0M7PooQenJ6JcA.png" /><figcaption>populate specific values</figcaption></figure><p>Mongoose Populate comes with a second parameter that is referred to as select, It allows the specifying of the return value from the referenced schema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*jpiTr-ELEN42-zRnVeIi_A.png" /><figcaption>returned value</figcaption></figure><h3>Conditional Query Using Populate</h3><p>Let’s say I want to return the job value that its name equals web developer, inside the getUser Populate method, let’s adjust it as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*0MvOJZTxWXabsniuWKtYdQ.png" /><figcaption>condition populate</figcaption></figure><p>Populate arguments are position-based, and it’s fixed. The third argument is the model name — jobs and the last argument — match is where the condition lies. So, it should only return jobs that match the specified name — web developer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*Z3gEWmhs2IQcQLPvErkWdQ.png" /><figcaption>return result</figcaption></figure><h3>Populate Nested Document</h3><p>Mongoose Populate allows a deep search of the referenced document, Let’s take a look at how to populate the name, gender, and email of the staff inside the HR sections property of the jobs schema and leaving others behind as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*ZurmKSTKJ3r03orGuzhpqw.png" /><figcaption>populate nested documents</figcaption></figure><p>Populate provides a populate property for querying nested documents— jobs sections. The sections.HR is an array that has the unique identifier of the staff the user works with.</p><p>When destructuring the populate method, it gives select more power to specify fields to include and exclude using the minus(-) followed by the name of the property — _id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*z8P1f4qa8W8pG8KZGs7SBw.png" /><figcaption>return HR Populated Value</figcaption></figure><h3>Populate Multiple Sub Documents</h3><p>Let’s take a look at how to populate all the jobs section&#39;s staff details as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*aCsHPxOHvgY6z1BZ5Xsz6Q.png" /><figcaption>populate multiple sub-documents</figcaption></figure><p>I accessed the jobs schemas, returned jobs that matched the specified name, went into the sections, and returned the specified staff details in each section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*fz6yIXDt-TRRES3PtXWwCA.png" /><figcaption>populate multiple sub-document result</figcaption></figure><p>Note: For schemas that have multiple referenced schemas, you may want to chain another populate method along with the initial populate method and every other thing applies.</p><h3>Conclusion</h3><p>It is obvious you have seen all I achieved using the Mongoose Populate Method, I believe that you have learned a better way to link your schemas, build schema structure, schema referencing and query deeply nested sub-documents. Would you be making use of this great Mongoose Populate Method any time soon? Yes! So have fun while at it.</p><p>If this article was helpful to you, kindly clap, like, comment, share, and follow me on my <a href="https://www.linkedin.com/in/chime-princewill-3a2b1b192/">Linkedin</a> and <a href="https://princewillchime43.medium.com/">Medium</a> to see more of my articles. Click the following link to access the <a href="https://github.com/chibuike07/mongoose_populate">source code</a>.</p><p>Feel free to drop any suggestions/comments. If you have a topic based on the Javascript/React.js ecosystem, kindly reach out and I’d be glad to write on it. Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bd0e6e60350" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/mongoose-populate-the-query-method-that-will-amaze-you-6bd0e6e60350">Mongoose Populate: the query method that will amaze you.</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React State Management: An Approach You Missed]]></title>
            <link>https://blog.devgenius.io/react-state-management-an-approach-you-missed-adabdf077eb8?source=rss-ca30ca69cc7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/adabdf077eb8</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Chime Princewill]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 11:42:04 GMT</pubDate>
            <atom:updated>2024-06-04T06:33:21.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bifnYRLNCwB8YSGM" /><figcaption>Photo by Evan Wise on Unsplash</figcaption></figure><h3>Introduction</h3><p>Being a ReactJs developer, you would agree with me that managing data in a global store for use across a project is an essential aspect of ReactJs . It reduces the way props are passed to child elements to improve efficiency across the product.</p><p>Are you a junior/senior developer who wants to focus just on the logic your project needs, and write mutative state functions and less complicated code in other to set a state for your project? this article is for you.</p><h3>Things to Learn</h3><p>In this article, I will show you how I handle the following:</p><ul><li>Reduce props drilling</li><li>Focus on state logic</li><li>Write mutative immutable update logic</li><li>Create entire slices of state automatically</li><li>Configure a simple redux store</li><li>Local storage</li><li>Best practices of ReactJs</li></ul><h3>Prerequisite</h3><ul><li>Know Javascript</li><li>Know ReactJs</li><li>Install Npm/Node</li></ul><h3>Setting Up Environment</h3><p>To create a new react project, use the following<a href="https://create-react-app.dev/docs/getting-started/"> <strong><em>link</em></strong></a>, and name it react_state_management. In your terminal, navigate to the desktop folder and install the following as shown below:</p><pre>npm i react-redux @reduxjs/toolkit styled-components --save</pre><h3>Folder Structure</h3><p>Let’s go into the src directory and create the following directories and files as follows:</p><pre>Components<br>  SearchLayout<br>    SearchLayoutStyles.js<br>    SearchLayout.jsx<br>  TodoCard<br>    TodoCardStyles.js<br>    TodoCard.jsx<br>Store<br>  index.js<br>  todoReducer.js<br>View<br>  Main.js<br>store.js<br>Util<br>  todoUtil.js<br><br></pre><p>In the above snippet, three main directories were created, each nested directory holds the styled-components styles and the other holds the element components.</p><h3>Setup the Store</h3><p>Inside the todoReducer file, create an initial state as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*LgYY4hpC3X5Sbs4tkhZoAQ.png" /><figcaption>initial state</figcaption></figure><p>Items is an array that will hold all the user todo while the errors is a variable that stores the error message to be displayed to the user. Let’s configure the reducer and set the initial state as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*cXUYGtgS5Ca_J7XOmX5SDw.png" /><figcaption>Create slice</figcaption></figure><p>Unlike the normal convention of creating a reducer — creating a function that returns a switch method for all the reducer actions, using redux-toolkit makes it a lot more flexible. it uses the createSlice method to configure all the reducers, types and actions right in one place, letting me focus on the logic only.</p><p>For every Slice, a unique name is defined. It uses the name to automatically create the types for every reducer defined in the slice reducers property — addTodo action.</p><p><strong>Note</strong>: For every reducers method, the state and action is exposed as a parameter to that method.</p><h3>Exposing Reducers and Action for Consumption</h3><p>After creating a slice, the following code snippet is added right after the createSlice as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*eg22Mh44vlP00fBaj1qH-Q.png" /><figcaption>expose slices and reducer</figcaption></figure><p>The reducers method — addTodo was destructured from the todoViewSlice.actions and the reducers method is exposed as well. The reducer function will be used inside the index file that was created above as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*1WOIZjJkMzBqL5BsWlvoDw.png" /><figcaption>root reducer</figcaption></figure><p>I love using combineReducers to be able to join multiple services reducers if need be. hence, I can import the todoReducer and assign it to the rootReducer directly. haven said that, reduce-toolkit accepts an object literal to hold multiple services reducers as well and it converts it to combineReducers in the background.</p><h3>Configure Store</h3><p>Add the following code snippet to the store file that was created above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*h59SNEG81TKWiwPj8Ai1Rw.png" /><figcaption>configure store</figcaption></figure><p>Unlike, the redux-thunk way, which needs a lot of setup, the redux-toolkit needs the code snippet above to set and it handles the browser devtool extension in the background.</p><h3>Provide Store to the Product</h3><p>Let’s go to the src index component to wrap the app component with the reducer provider as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*coihBX6LInP_mia-JeiPQQ.png" /></figure><p>With the snippet above, the reducers, and exported actions are now available in any of the components for use.</p><p>Let’s go inside the Main component and add the following code snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*pn8atY34dUjHpAxLTYPlGw.png" /><figcaption>main component</figcaption></figure><p>The component holds the two components that I will be creating shortly. The SearchLayout is the component that will hold the form aspect of the todo application while the Todo component will have a list of the added todos.</p><p>Inside the SearchLayout component, let’s add the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*Oz3erCUjILltjLeLeeklag.png" /><figcaption>container returned elements</figcaption></figure><p>This is basically a form field that has a text input that will allow the users to add their todos. the error variable is a global watcher that watches the application error status and displays it to the user.</p><h3>Create Todo</h3><p>Inside the SearchLayout component let’s add the following code snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*s9LBlH6zt-074HmJ9QnwhA.png" /><figcaption>created funtion</figcaption></figure><p>In the snippet above, I prevented the default behaviour of the form to avoid returning void.</p><p>When handling form fields, is essential that a check is made to verify that the user does not add empty todo data. So let’s create a reducer that will handle the display of errors as shown below inside of the todoReducers function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*XivzzFB4qYWcS3s8D4IIoA.png" /><figcaption>error toast</figcaption></figure><p>A toast was created and exported just like the addTodo reducer as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*cmwYhVQ7TaX-R5sFeA-8aQ.png" /><figcaption>exporting reducer actions</figcaption></figure><h3>Updating the Store</h3><p>Now let’s go into the submit handler of the Searchlayout component and consume the toastError action as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*Ng4qrXIug5D0ZcN2jY8N8Q.png" /><figcaption>add a todo to the global state</figcaption></figure><p>When updating the store, all that needed to be done was to import the reducer action that was exported earlier from the todoReducer file, and pass it to the dispatch function.</p><p>I know you would be wondering why there was no type, action and payload passed to the dispatch just the same regular way you may know:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*R9pbI3hNFTuHG43-doNBbA.png" /><figcaption>the regular way — old way</figcaption></figure><p>when using redux-toolkit, all that is needed to do is to pass the data/text inside of the actions — toastError and it will be seen as the payload to that very action.</p><h3>Watch for Duplicate Todo</h3><p>Let’s go into the src util file that was created above and add the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i937EzYiNrgniaaMfTXu9w.png" /><figcaption>find duplicate todo</figcaption></figure><p>A middleware that accepts two arguments was created, the data argument is the items while the todo is the current todo that the user wants to add to the list of items. the data— items were accessed and checked if the user had already added the same todo. Now let’s go into the submit handler and consume it as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuQ26bg-CKpHonUobk5b8g.png" /><figcaption>handle duplicate todo</figcaption></figure><p>If a duplicate todo is found, the toast is updated to hold the error message that will be displayed to the user. otherwise, let’s clear the toastError message and add a todo to the reduce store as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*l5wgWIVd8FAxA5nP-12emg.png" /><figcaption>add a todo to the store</figcaption></figure><p>A generated substring was concatenated with the random generated id .</p><h3>Render the User’s Todo</h3><p>Let’s go into the Todo component and get the items from the store as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*B1YMCVzSLVuoVJBArJaB5A.png" /><figcaption>todo component</figcaption></figure><p>When trying to access the store, the useSelector method that is imported from the reduce library is used for that. The store can hold many reducers so it&#39;s a good convention to only access the particular reducer that holds the todo — items</p><p>Now let’s loop through the items and render all the todo as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*DvlFJFdEalzmaJ1JzGLVgg.png" /><figcaption>render list of todo</figcaption></figure><p>A check was made to verify that the items array is not empty using the ternary operation and also render a text that displays if the user has no todo. afterwards, the renderTodo variable was passed to the container to be displayed to the browser as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*CJFlakLryN1B38XYFZAWng.png" /><figcaption>display todo list to the user</figcaption></figure><p>Let’s go to the browser and take a look at what is rendered as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JS_9cvOj6bgxe3ZYx-c0A.png" /><figcaption>todo display screen</figcaption></figure><p>I added some styles using the styled-component . There is no todo at the moment so it displays “no record found!” to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*08vk9cabIOCo6O-R3PXaIw.png" /><figcaption>todo lists</figcaption></figure><p>As we can see, the user is now able to add some todo and have an error message displayed below the form field to be aware of a duplicate todo/any other error.</p><p>It is an excellent convention to allow the user to perform mutations on the individual lists, so the two icons will be used to allow the users to perform the following actions — delete and update actions.</p><h3>Remove Specified Todo List</h3><p>Let’s go into the todoReducer file and add the following to the lists of reducers actions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*dVg26YE_tFOWMEguwOdPQg.png" /><figcaption>delete a single list of todo</figcaption></figure><p>When the user clicks on the delete icon the snippet above is called in the renderTodo snippet above, the id of the todo is passed as a payload and removed the specified todo from the lists of todo.</p><h3>Edit a Todo</h3><p>let’s go into the todo component and add the following middle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*tCb2Ve5DpWOT9rMVtQxjMw.png" /><figcaption>handleEdit</figcaption></figure><p>Once the user clicks on the edit icon, two states are set, setCanEdit which is a toggle that determines if the todo can be updated or not. The setIndex holds the current index of the specified todo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*8jEhDX6yeM8NebV4YsD-FA.png" /><figcaption>edit todo</figcaption></figure><p>When canEdit is true, the paragraph element that is in the same position as the current index of the todo that the user wants to edit is located. Afterwards, the user can click on the specified element and adjust the text in it.</p><p>Let’s prevent the user from updating todo to already existing todo as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*ZJx0R4u6AKiNlztETj3lBw.png" /><figcaption>set flag to watch when an update is made to the element holding the todo</figcaption></figure><p>After a user has adjusted the todo and clicked the edit icon, a check will be made to watch for duplicated todo and finally update the store as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*XzPIKJgYK9faKGzl-IIBJw.png" /><figcaption>save todo</figcaption></figure><p>Inside the todoReducer file, let’s create the editTodo reducer as shown below and export it like other reducers actions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*u_hxyNXlQUVPngx3j1l1EQ.png" /><figcaption>edit todo reducer</figcaption></figure><p>The items was looped and found the specified todo with the specified id and updated the items with the updated todo.</p><h3>Persist Todo Using Local Storage</h3><p>Currently, the todo lists do not persist after refreshing the browser. go into the util file and add the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*4YGmuqMpoA3KdcCiAEszvw.png" /><figcaption>DB storage using local storage</figcaption></figure><p>In the snippet above, all that the dbStorage is doing is to simply set the current state of the items to the local storage. if it exists, it saves it to the local storage else it creates a database and saves items to the local storage.</p><p>Let’s import the dbStorage into the Todo component to watch when there is an update to the items in the store and save it to the local storage as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*XZNQws33hiSVr-QFmJt2nA.png" /><figcaption>save data to the local storage</figcaption></figure><h3>Fetch Todos from the Local Storage</h3><p>When the SearchLayout component is mounted, there is a need to check if there is any data in the local storage and fetch the data to be saved in the store . Let’s go into the util and create a middleware that will fetch data from the localstorage as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ShQdJoCHqEoIqpfvcL3-IQ.png" /><figcaption>fetch data from the local storage</figcaption></figure><p>and let’s import it into the SearchLayout component on mount as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*0ASBKnUEZfI5tgYOqQp89A.png" /><figcaption>fetch todo on mount from local storage</figcaption></figure><p>Let’s take a look at the <a href="https://m.youtube.com/watch?v=YB8jDtWU6c8&amp;list=PLu70M_u3InWjJ6n6h8fjlKUUF9N-tLWK1&amp;index=3&amp;t=26s&amp;pp=gAQBiAQBsAQB">demo</a> and see how it looks. You would agree with me that the application is an exceptional todo application.</p><h3>Conclusion</h3><p>Finally, the state of the todo application was managed efficiently, the state was set up using a less complex setup, I focused on the logic of the application and created mutative immutable updates to the state.</p><p>Going forward I believe that you will start using the redux-toolkit to manage/set up your state.</p><p>If this article was helpful to you, kindly like, comment, share and follow me on my <a href="https://www.linkedin.com/in/chime-princewill-3a2b1b192/">Linkedin</a> and <a href="https://princewillchime43.medium.com/">Medium</a> to see more of my article. Click the following link to access the <a href="https://github.com/chibuike07/state_management_with_redux_toolkit">source code</a> and don’t forget to give it a star.</p><p>Feel free to drop any suggestions/comments. If you have a topic based on the Javascript/React.js ecosystem, kindly reach out and I’d be glad to write on it. Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adabdf077eb8" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/react-state-management-an-approach-you-missed-adabdf077eb8">React State Management: An Approach You Missed</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mongoose Aggregation In Nodejs: the query master]]></title>
            <link>https://faun.pub/mongoose-aggregation-in-nodejs-the-query-master-5e2ad3a0d1da?source=rss-ca30ca69cc7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e2ad3a0d1da</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Chime Princewill]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 11:29:29 GMT</pubDate>
            <atom:updated>2024-06-04T06:32:11.088Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2rtG8zRpKCNAh55m" /><figcaption>Photo by <a href="https://unsplash.com/@jennyueberberg?utm_source=medium&amp;utm_medium=referral">Jenny Ueberberg</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Mongoose aggregation is a powerful feature provided by the Mongoose library for MongoDB in Node.js. It allows you to perform complex data manipulations and transformations on MongoDB collections using a pipeline of stages.</p><p>You should know Mongoose aggregation if you are working with MongoDB and need to perform advanced data analysis, reporting, or data processing tasks. Aggregation provides a way to combine, filter, transform, and analyze data in a flexible and efficient manner.</p><p>Are you working with MongoDB and Node.js? Are you a data analyst, and database administrator who must work with large datasets and perform complex data operations in the backend using nodejs? Then this article is for you.</p><h3>Things To Be Covered</h3><blockquote>For this article, I will be guiding you on how to use the following aggregation pipelines using an Author Management API:</blockquote><ul><li>match</li><li>lookup</li><li>project</li><li>group</li></ul><h3>Prerequisites</h3><p>Prerequisites for learning Mongoose aggregation includes:</p><ul><li>A basic understanding of MongoDB,</li><li>Basic knowledge of Node.js,</li><li>install MongoDB compass</li><li>and the Mongoose library.</li><li>Familiarity with JavaScript and JSON is also helpful.</li></ul><p>I will be using Microsoft visual studio code(vs code) for this article, feel free to use any of your choices.</p><h3>Set Up Environment</h3><p>To start up, let’s navigate to the terminal and install the following in the code snippet below:</p><pre>cd desktop<br>mkdir mongoose_aggregration<br>cd mongoose_aggregration<br>npm init -y<br>npm install mongoose express cors dotenv<br>code .<br></pre><p>In the code snippet above, I navigated to the desktop directory and created a directory named mongoose_aggregration , I went into the folder and initialize package.json with its default configuration. I then installed the necessary packages that will be needed and finally opened the directory in vs code.</p><p>Let’s go into the package.json file and adjust the script property as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*21CzvRsVW-R9WTThVG_qvg.png" /></figure><h3>Starting Up The Server And Connecting to the Database</h3><p>To set up a node server and connect to your MongoDB kindly use the following <a href="https://blog.devgenius.io/mongoose-discriminator-an-easy-way-to-inherit-schema-properties-6c6e89c3795?source=user_profile---------5----------------------------"><em>link</em></a><em>. </em>Let’s check if everything is fine by running dev in the terminal as shown below:</p><pre>npm run dev</pre><p>If you see the code snippet below, you have successfully started a server and connected to the MongoDB database.</p><pre>server ready on 4000<br>connected successfully</pre><h3>Folder Structure</h3><p>Let’s go into the root directory and run the following as shown below:</p><pre>mkdir controller routes model<br><br>cd model<br><br>touch coreModel.js author.js follower.js books.js<br><br>cd ..<br><br>cd controller <br><br>touch authorServices.js bookServices.js followerServices.js<br><br>cd..<br><br>cd routes<br><br>touch authorServices.js bookServices.js followerServices.js</pre><p>In the code snippet above, I created three folders in the root directory and create files into the folders accordingly.</p><h3>Schema Design</h3><p>Inside the coreModel.js let’s create a model that will handle common schema properties as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*BPhX3BJy1Oriboe34HTNvQ.png" /><figcaption>core Model</figcaption></figure><p>The coreModel schema handles the name and photo property which will be shared amongst other schemas that I will be creating shortly. I set a discriminatorKey that will be used to identify the schemas individually.</p><p>Do you want to know more about discriminatorKey / schema inheritance, I have written an article on it, which can be found <a href="https://blog.devgenius.io/mongoose-discriminator-an-easy-way-to-inherit-schema-properties-6c6e89c3795"><em>here</em></a></p><h4>Author Schema</h4><p>Inside the author.js , let’s add the following code snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*cEo5lWhLyqmIAT3HroFjUg.png" /><figcaption>author schema</figcaption></figure><p>The coreModel is imported and I passed the unique identifier and the schema using the <a href="https://blog.devgenius.io/mongoose-discriminator-an-easy-way-to-inherit-schema-properties-6c6e89c3795">discriminator</a> property of the coreModel . Haven did this, it would enable me to only define the other author&#39;s properties that are unique to them and <a href="https://blog.devgenius.io/mongoose-discriminator-an-easy-way-to-inherit-schema-properties-6c6e89c3795">inherit</a> the name and photo property from the coreModel .</p><h4>Books Schema</h4><p>An author should be able to have a book and followers, let’s also create a model that will handle them as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRABe5yYR2bGaWFKDiVEjg.png" /><figcaption>book schema</figcaption></figure><p>Just like the author’s schema, only the unique book properties are created and the name and photo properties will be <a href="https://blog.devgenius.io/mongoose-discriminator-an-easy-way-to-inherit-schema-properties-6c6e89c3795">inherited</a> from the coreModel</p><h4>Followers Schema</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2xRnCm6DZ-M72Qv33Vf6OQ.png" /><figcaption>followers schema</figcaption></figure><p>Unlike the author and books schema, nothing was inherited from the coreModel schema. It handles the followers of the authors and have them drop a comment along.</p><h3>Creating of Controllers</h3><p>Inside the authorServices.js file, let’s add the following to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-PRF6IVECm6agCs6k2M2rQ.png" /><figcaption>author service handler</figcaption></figure><p>I used a class base controller and created the createAuthor method that will handle the creation of an author. A check was made to verify if the author already exists, and I used the trycatch method to watch out for any server error while trying to save the author to the database.</p><h3>Creating Routes</h3><p>Let’s try and create a route that will handle the authorServices controller as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*NM3w-saP-HG0Iz0CWXnjyw.png" /><figcaption>author service route</figcaption></figure><p>The AuthorServices class was imported and a new instance was created from it so we could have access to it&#39;s methods and the createAuthor method was passed into the post method of the router.</p><p>Finally, the router was imported to the server.js to be used as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*GnQthQyMTyOB8DCEpW2a5Q.png" /><figcaption>using author router</figcaption></figure><h3>Making Request withIn VsCode</h3><p>Moving forward, I will be using a vscode extension called:</p><pre>httpYac - Rest Clientv5.5.6 By Andreas Weber</pre><p>To get started with the vscode extension above, all that’s needed is to create a file with an http-extension(filename.http), and follow the <a href="https://marketplace.visualstudio.com/items?itemName=anweber.vscode-httpyac">guideline</a> to get started</p><p>Inside the file — reques.http, let’s create a new author as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*_Uj3jYXmwsZTcIZl-0lPcQ.png" /><figcaption>create author request</figcaption></figure><p>HttpYac allows you to declare a global variable and use them as shown in the snippet above. I made a post request, set the headers and passed the global variables in the body of the request.</p><h4>Get the Authors (Match stage)</h4><p>Match Pipeline filters the documents based on a specified condition. Let’s add the code snippet as shown below inside of the AuthorServices class I declared above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jUf0ljubkCD73o5ah1243A.png" /><figcaption>get authors</figcaption></figure><p>To use Mongoose aggregate, I have to use the aggregate method that comes with the model , it accepts an array and has all the pipelines/stages as an object in it.</p><p>The Match stagewas used to get all the authors that have the _id property. Mongoose Aggregate returns an array so I checked to know if an author was found, and get the authors data from the MongoDB database</p><p>Inside the authorServices route, let’s chain the get method to the route as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ibs_3_45fZezgUQABtAdqw.png" /><figcaption>author route</figcaption></figure><p>Let‘s take a look at how the data that was created looks in the code snippet below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*qtQIpHV-lGQlGaUJIkJqYw.png" /><figcaption>author data</figcaption></figure><h4>Create Books</h4><p>Let’s go into the bookServices.js file and add the following code snippets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TfcdcQTIRxxGwdyD_w2J8A.png" /><figcaption>create a book</figcaption></figure><p>Just like the authorServices.js , a book class was created and saved the book data to the database.</p><p>Note: the follower&#39;s controller/routes will be in line with the other controllers I created above.</p><h4>Using Lookup Stage</h4><p>lookup stage is used to perform a left outer join with another collection. Let’s add the code snippet as shown below inside of the BookServices class I declared above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*JwTecbM26i8grCojK3gk7w.png" /><figcaption>get books by the same authors</figcaption></figure><p>In the snippet above, I used the match to get an author whose _id properties match the Id of an author that was sent as a query and got all the books of the specified author using the lookup stage</p><p>The Lookup stage can take up to six fields but let’s look into the once that was used as listed below:</p><ul><li>from: takes up a collection name to access. In this case, the coremodels collection</li><li>localField: takes up the fields to match the collection that the aggregate method was called upon. In this case, it was the author model</li><li>foreignField: takes up the field that is inside of the collection I added in the from above — coremodels collection</li><li>as : represent a name that holds the return value of the lookup stage — authorsBook</li></ul><p>Inside the authorServices route, let’s chain the get method to the route as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ml2MlqgOaLu1mQdYayPPdw.png" /></figure><p>The above books request will return the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*WWltQadNS7isUF8Ag17mGg.png" /><figcaption>lookup result</figcaption></figure><p>In the code snippet above, It returns the author’s data, and inside of the authorsBook is where the lookup result was set. Remember, what I wanted to do is to get just the books of the author and not the author’s properties too.</p><h4>Using Project Stage</h4><p>Project stage specifies the fields to include or exclude in the output documents. So let’s add the following code snippet into the getBooksByAuthor method of the Books class using project stage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*VNW37jBnQ9jnKaBViBj1pQ.png" /><figcaption>the project stage</figcaption></figure><p>Aggregate query uses the dollar sign($) to access its variables/document properties, so all I had to do was to create a field and assign it the output field name to return to the client. Let’s take a look at the returned result below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*M-ORjKfhHNXnUzi6WGlF4w.png" /><figcaption>project author’s books</figcaption></figure><h4>Using Group Stage</h4><p>Groups stages arranges the documents by a specified field and performs aggregation operations on each group. Let’s create a new method inside BookServices class that gets all the books of the individual authors, names of the authors and followers as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*gPpWB4GXqg1hb8jiT6cWtA.png" /></figure><p>I combined the lookup stage which gets all authors, the group stage were used to separate the individual authors using their _id and defined a variable for the group fields.</p><p>When using group staging, it only allows the _id field to be passed directly while others need an accumulator($first) to add other fields as shown in the code snippet above.</p><p>Let’s take a look at the code snippet below to see what data was returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LvAw40Us58PtMPhlm-XEfg.png" /><figcaption>the combine stages</figcaption></figure><p>The snippet above gets us the authors _id , names, books of the individual authors and their followers if any.</p><h3>Summary of Mongoose aggregation:</h3><p>Mongoose aggregation is a powerful feature that allows you to perform complex data manipulations and transformations on MongoDB collections. It is helpful for advanced data analysis, reporting, and data processing tasks.</p><p>I believe that going forward, you will start using Mongoose aggregate for querying data from the mongoDB database.</p><p>If this article was helpful to you, kindly clap, like, comment, share and follow me on my <a href="https://www.linkedin.com/in/chime-princewill-3a2b1b192/">Linkedin</a> and <a href="https://princewillchime43.medium.com/">Medium</a> to see more of my articles. Click the following link to access the <a href="https://github.com/chibuike07/mongoose_aggregation">source code</a> and kindly give me a <strong><em>star</em></strong>.</p><p>Feel free to drop any suggestions/comments. If you have a topic based on the Javascript/React.js ecosystem, kindly reach out and I’d be glad to write on it. Thanks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ayFZ20zExMFQT54t.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e2ad3a0d1da" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/mongoose-aggregation-in-nodejs-the-query-master-5e2ad3a0d1da">Mongoose Aggregation In Nodejs: the query master</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Custom Star Rating Component Using React Hooks: the moment of Truth!]]></title>
            <link>https://blog.devgenius.io/how-to-build-a-custom-star-rating-component-the-moment-of-truth-1c60d8ba7ff7?source=rss-ca30ca69cc7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c60d8ba7ff7</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[5-star-rating]]></category>
            <dc:creator><![CDATA[Chime Princewill]]></dc:creator>
            <pubDate>Wed, 31 May 2023 15:31:16 GMT</pubDate>
            <atom:updated>2023-06-01T16:40:41.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rwhpb4AiNfA7_qlU" /><figcaption>Photo by <a href="https://unsplash.com/@ospanali?utm_source=medium&amp;utm_medium=referral">OSPAN ALI</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Customizing components has been a recommended way to create reusable UI in single-page applications like ReactJs and other UI libraries.</p><p>Most applications often wish to get the users&#39; feedback on how they feel when accessing their software applications. It is also a key feature that is added to most e-commerce projects - to rate a product/vendor/user.</p><p>Are you a front-end developer who wishes to add the rating feature to his/her software application? Are you tired of using third-party libraries to implement star rating? You may want to look into this article.</p><h3>Things to Learn</h3><p>In this article, I will show you how I will handle the following:</p><ul><li>Create a custom star rating</li><li>How to use Fontawesome</li><li>Best code practices</li></ul><h3><strong>Prerequisites</strong></h3><ul><li>Install Node and Npm</li><li>Know Javascript</li><li>Know Reactjs Basics</li></ul><p>I will be using visual studio code for this tutorial but feel free to use any code editor of your choice.</p><h3>Setting Up Environment</h3><p>To create a new react project, use the following<a href="https://create-react-app.dev/docs/getting-started/"> <strong><em>link</em></strong></a>, and name it <strong><em>custom-star-rating-with-react</em></strong>. In your terminal, navigate to the desktop folder and install styled-components as shown below:</p><pre>cd desktop cd custom-star-rating-with-react <br>yarn install styled-components <br>code .</pre><h3>Folder Structure</h3><p>Go into the desktop folder and run the following commands:</p><pre>cd src <br><br>mkdir Asset Component Util<br><br>cd Commponent <br><br>touch CustomRating.jsx Item.jsx<br><br>cd ..<br><br>cd Util<br><br>touch data.js</pre><p>In the snippet above, I went into the src folder and created three different folders. Inside the Component folder, I created the CustomRating.jsx , Item.js and finally, I went into the Util folder and added a dummy data called item.</p><h3>Creating The Custom Star Rating</h3><p>Let’s go into the customRating.jsx and add the following code snippet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WwYA1wgubPVcA-3Yih_-qw.png" /><figcaption>customRating component</figcaption></figure><p>I created a customRating component that renders the stars. An array of lengths of five was generated to specify the five stars to be rendered. The rating variable is a state that will handle the stars that will be selected by a user. A canSpin props was passed to determine when a star can spin or not.</p><p>The goal will be to make the stars spin when it&#39;s not selected and stop once selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*pYk1mdLXp_4HYxgmOuSdvA.png" /><figcaption>the stars</figcaption></figure><h3>Activating and Deactivating the Stars</h3><p>To select a star, the user would want to highlight the stars on hover, so let’s add the following as shown below in the customRating component</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*Z_vBUJH6t5vagYAfrIiAZA.png" /><figcaption>the state</figcaption></figure><p>I created two states, rating that will handle the stars selected and the hover that will handle highlights of the individual star that will be hovered upon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*Wiv7vuw5CMHHYPYnEPFg4w.png" /><figcaption>hover</figcaption></figure><p>The onMouseEnter and OnMouseLeave events were used to set the state of the hover, from the first star to the current star. The ratingValue is the value of the highlighted/selected star. It is defined inside the loop above as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*4Gxx6f9M4eNmQgr_Ufiwbg.png" /></figure><p>An array index starts from an index of zero, so I had to add one to each index. Currently, the index now starts from an index of one.</p><p>The two state variables were used as a flag to set different colours on mouseEnter and mouseLeave .</p><h3>Selecting a Specified Star</h3><p>Currently, users can now hover over the stars they want to select and it will switch to an orange background colour. Now let’s work on making the stars to be clickable by adding the following code snippet to the customRating component :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*u9RKj-EcPpe_UrV8OBxsew.png" /><figcaption>set rating</figcaption></figure><p>An onClick method of the FontAwesome component is used to set the specified starsindex value that the user selects to the state. your browser should look as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*CQvJZEN9RXhmDJdDpB009A.png" /><figcaption>star when clicked</figcaption></figure><h3>Implementing The Custom Rating</h3><p>Having seen this, let’s use the customRating component into the Item component that was created above as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*DVyhndnt5FDFvtvTi5BXKw.png" /><figcaption>item component</figcaption></figure><p>A food cart was created and the stars were imported for use in the Item component. Your browser should look like the snippet below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vKxrnZkng8-zWi-COrdkeQ.png" /><figcaption>implementation of the custom rating</figcaption></figure><h3>Conclusion</h3><p>Finally, A custom star rating has been created and used in another component. Going forward, I hope you will start creating your own custom star rating and have it implemented appropriately.</p><p>If this article was helpful to you, kindly like, comment, share and follow me on my <a href="https://www.linkedin.com/in/chime-princewill-3a2b1b192/">Linkedin</a> and <a href="https://princewillchime43.medium.com/">Medium</a> to see more of my article. Click the following link to access the <a href="https://github.com/chibuike07/star_rating">source code</a> and don’t forget to give it a star.</p><p>Feel free to drop any suggestions/comments. If you have a topic based on the Javascript/React.js ecosystem, kindly reach out and I’d be glad to write on it. Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c60d8ba7ff7" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/how-to-build-a-custom-star-rating-component-the-moment-of-truth-1c60d8ba7ff7">How to Build a Custom Star Rating Component Using React Hooks: the moment of Truth!</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Form Using React Hooks: The boss of the senior bosses]]></title>
            <link>https://blog.devgenius.io/dynamic-form-using-react-hooks-the-boss-of-the-senior-bosses-24cecc3da4a7?source=rss-ca30ca69cc7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/24cecc3da4a7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[dynamic-form]]></category>
            <dc:creator><![CDATA[Chime Princewill]]></dc:creator>
            <pubDate>Fri, 07 Oct 2022 10:45:56 GMT</pubDate>
            <atom:updated>2024-06-04T06:34:03.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M_pdSWXKT97Z0dz_" /><figcaption>Photo by <a href="https://unsplash.com/@javaistan?utm_source=medium&amp;utm_medium=referral">Afif Ramdhasuma</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Interest in digital awareness has dramatically increased, and web application is one of the great ways to build and design a software application to solve one human challenge or the other. Collecting users’ data is one area of development that can not be overlooked.</p><p>Are you a junior/senior software engineer who wants to collect data in chunks using form fields and watch out for individual changes using react hooks? Then this article is for you.</p><h3>Things to Learn</h3><p>In this article, I will show you how I handle the following:</p><ul><li>Render dynamic forms</li><li>Handle the changes in all forms</li><li>Using a button to add more forms</li><li>Using a button to remove forms</li><li>Use styled components</li><li>Best code practices</li></ul><h3>Prerequisite</h3><ul><li>Know Javascript</li><li>Know ReactJs</li><li>Install Npm/Node</li></ul><h3>Setting Up Environment</h3><p>To create a new react project, use the following<a href="https://create-react-app.dev/docs/getting-started/"> <strong><em>link</em></strong></a>, and name it dynamic-forms. In your terminal, navigate to the desktop folder and install styled-components as shown below:</p><pre>cd desktop</pre><pre>cd dynamic-forms</pre><pre>npm i styled-components ––save</pre><pre>Code .</pre><p>In the snippet above, I navigated to the desktop folder, went inside to the dynamic-forms, react project I created and installed styled-components for a flexible styling of the application.</p><h3>Folder Structure</h3><p>Let’s go to the terminal and run the following code snippet:</p><pre>cd src</pre><pre>mkdir View</pre><pre>cd View</pre><pre>mkdir Styles Util</pre><pre>cd Styles</pre><pre>touch ViewStyles.js</pre><pre>cd ..</pre><pre>cd Util</pre><pre>touch handlers.js</pre><pre>cd ..</pre><pre>touch Main.js</pre><pre>cd ..</pre><p>I navigated inside the src folder, and created a folder named View, inside the View folder, I created two folders named Styles, Util and a component named Main.js. Inside the Styles folder, I created a file named ViewStyle.js, and inside the Util I created handlers.js.</p><p>Let’s go into the app.js and remove the returned jsx, leaving just the div elements with the class of App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/0*ZBfDP2A8Omwr8zu8" /></figure><p>let’s go into the app.css and removed all the style properties, and add a default styling as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/0*0wQCv8Vy2wZWIhzC" /></figure><h3>Render dynamic form</h3><p>Inside the Main component, I created above, let’s add the following code snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*otyTvmfJvCz__ZSq" /></figure><p>In the snippet above, I rendered a heading and a form that hold an input field. formField is a state that handles all the form fields, currently, only one field is rendered.</p><p>Note that the markups were generated using styled-components as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/0*IJtArOHtgIeKfvih" /></figure><p>Earlier, I mentioned that I was going to have a button that will be used to add/remove any specified form. Let’s add the buttons as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*GYDzlDRBZ68zBiZq" /></figure><p>Because React only accepts one child on its return, I created a wrapper to wrap the field and the buttons. For every loop, it wraps an element that holds the field and the buttons.</p><h3>Integrate Fontawesome Icons</h3><p>The button icons were added using the font awesome icon-v5.15.4 and I used the CDN which I linked inside the index.html as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RtjQ-aRSyh-PKiev" /></figure><p>The snippet above allows me to add icons using the className attribute as shown in the previous code snippet.</p><h3>Add More Forms On Button Click</h3><p>Let’s go into the handlers.js file I created above and add the following code snippet to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*SoL4grlnEL4l_4M5" /></figure><p>I declared/exported a handleAddForms function that holds two parameters, the events, and a method that sets the state of the form fields. I used the preventDefault method of the event to prevent the form from returning void and spread the prev state and add an empty string to the state.</p><p>The setFormField is declared in the Main component as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/0*HKUopeDAzSU04IY2" /></figure><p>The handleAddForms is imported into the Main component and passed in the onClick method of the span element and set the arguments as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/0*dvVRjTDUwkjZ6atX" /></figure><h3>Remove Form On Button Click</h3><p>Let’s go into the handlers.js file and add the following code snippet to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pjt9WL3G3u_qglV9" /></figure><p>In the snippet above, I declared/exported the removeForm handler, I passed four(4) arguments to it, the events that were triggered, the index of the specified field, the current fields and a method that sets the state.</p><p>I prevented the form from returning void, I set criteria to watch out for when the fields are left with one field and stop executing the rest of the code after the condition.</p><p>I looped through the formField to get the one that was specified using the index and returned the rest of the field aside from the specified field and finally set the state to the currently available fields.</p><p>The removeForm method was also imported in the Main component and was passed to the remove button onClick on the button as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*dCFJurJISFiQTlWi" /></figure><h3>Handle Form Change</h3><p>Let’s go into the handler.js file and add the following code snippet to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*MLujz7ylousiQz2F" /></figure><p>In the snippet above, the specified index was used to get the exact field to update and finally returned the new updated field to the state. The parameters were set in the Main component where the function was called.</p><p>Let’s go into the Main component and passed the function in the onChange method of the fields and set the value to the value of each field as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/0*zAqTC6LnPDvrw2-U" /></figure><h3>Demo</h3><p>Now that I have added all the above, let’s use the following link to access the <a href="https://res.cloudinary.com/hobbyluv07/video/upload/v1663142264/dynamic_forms_-_Google_Chrome_2022-09-14_08-50-50_pghjpd.mp4">demo</a></p><h3>Conclusion</h3><p>By now, I guess you must have viewed the demo, and seen how flexible and easy it was to interact with the forms. I guess that your e-commerce site and other UI designs that need a dynamic form will no longer be a challenge going forward.</p><p>If this article was helpful to you, Kindly like, comment and follow me on<a href="https://www.linkedin.com/in/chime-princewill-3a2b1b192/"> Linkedin</a> and<a href="https://princewillchime43.medium.com/"> Medium</a> to see more of my articles. Click on the following link to access the source<a href="https://github.com/chibuike07/dynamic-form-react"> <strong><em>code</em></strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24cecc3da4a7" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/dynamic-form-using-react-hooks-the-boss-of-the-senior-bosses-24cecc3da4a7">Dynamic Form Using React Hooks: The boss of the senior bosses</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mongoose Discriminator: An easy way to inherit schema properties]]></title>
            <link>https://blog.devgenius.io/mongoose-discriminator-an-easy-way-to-inherit-schema-properties-6c6e89c3795?source=rss-ca30ca69cc7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c6e89c3795</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[schema-design]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Chime Princewill]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 09:09:05 GMT</pubDate>
            <atom:updated>2024-06-04T06:34:49.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NWVPIZ0rM2f8wcdH" /><figcaption>Photo by <a href="https://unsplash.com/@cmrnrd?utm_source=medium&amp;utm_medium=referral">Cam</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Nowadays, the building of server structure cannot be overemphasized, due to the high services to please client demands, the structure tends to grow bigger over time, thereby, calling for a backend engineer with good knowledge of how to design a good model for an application.</p><p>I am a Mern Stack Engineer and believe me, I know how this can get someone crazy as the demand increases if not handled properly.</p><p>As a backend engineer, you may have wished to overcome repeating of same properties in double/multiple scheme structures, in order to increase the server performances. Yes, I know you would say, the ref property of a schema can do that.</p><p>Also, you may have tried creating a user schema — client/admin, and want to save them as one collection, but with different properties.</p><p>Are you a backend engineer that builds API structure using restful API, and manages data using MongoDB? If you have been looking for a solution to cut down the above-mentioned to improve performance, work smart, and learn best code practices then this article is for you.</p><h3>Things to Learn</h3><p>In this article, I will guide you through how to do the following:</p><ul><li>Handle the building of schema structures that should have similar properties</li><li>Inherit properties of another schema with ease using mongoose discriminator,</li><li>Building API gateway</li><li>Use vscode for API requests</li></ul><h3>Prerequisite</h3><ul><li>Know Javascript</li><li>Know NodeJs/Expressjs</li><li>Install node/npm</li></ul><h3>Setting Up Your Environment</h3><p>To start up, let’s navigate to the terminal and install the following in the code snippet below:</p><pre>cd desktop</pre><pre>mkdir mongoose_discriminator</pre><pre>cd mongoose_discriminator</pre><pre>npm init -y</pre><pre>npm i express cors dotenv mongoose</pre><pre>Code .</pre><p>I went into the desktop folder and created a folder named mongoose_descriminator, inside it, I initialized the package.json file with the default entries, installed the packages I will be using and finally opened the folder in vs code.</p><p>Let’s go into the package.json file and adjust the script property as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/0*cdczdNmoEuws5OWG" /></figure><p>In the snippet above, the start property will start up the server with the current change of the server without looking out for subsequent change while the dev property, using nodemon that was installed in the previous snippet, handles the subsequent change of the server.</p><p>The Index.js file is where I will be starting up my server. Note that those properties are shot hands for us not to run the values of the properties in the terminal.</p><h3>Starting Up the Server</h3><p>In the root folder, I will create the index.js file I used as a value to the scripts properties and add the following code snippet to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*LDxYLsmLTztVq2j2" /></figure><p>I imported the app file, which will hold every other configuration that does not consign starting up and connecting the server with the database(MongoDB). I will be putting all the important variables in the env environment. I required the dotenv config to access the env variables where needed.</p><p>The port is set to hold the port I want the server to run on or any port specified by the hosting firm — Heroku and finally, I set a listener to know when the server is up and running.</p><h3>Connect to the MongoDB database</h3><p>To connect our application to the database, add the following code snippet to index.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*G1AvYFEWpaZhVUzR" /></figure><p>In the above snippet, I set the options needed to establish a connection to MongoDB using mongoose. This option is set as an argument to the mongoose connect method as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D53W3fi9kkqWIHJa" /></figure><p>I accessed the environment variables and got the development and production URI for the MongoDB connection. The mongoose connect method accepts two arguments, options and Uri. I passed the two arguments as required in the mongoose connect method.</p><p>It returns a promise, after being resolved, In my case, I printed a success message once it connected successfully and catch any error if it fails to connect.</p><p>Note that all that I have added for connecting my server to MongoDB comes before the “app.listen” method above.</p><h3>Adding Criterion</h3><p>Now that I am connected to the database and started the server, let’s create a file named app.js and add the following criterion as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*rr9BP0-4sNa2RnbT" /></figure><p>I defined my global variables, <a href="https://expressjs.com/en/starter/installing.html">express</a>, and <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">cors</a>, and declared the app variable to hold the express methods. Note that the app variable was what I imported in the index.js file above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WBONLkVWGZaDb8OC" /></figure><p>In the above snippet, I destructured the environment variables, set the allowed URLs (client) that can perform a request to the server using the app.use(cors()) method, and parsed the body of the request using the express.urlencoded and express.json().</p><p>If you are with me, go to the terminal, and let’s start the server as shown below:</p><pre>npm run dev</pre><p>If you are seeing the code snippet below, you have successfully started a server and connected to the MongoDB database.</p><pre>server ready on 3000</pre><pre>connected successfully</pre><h3>Folder Structure</h3><p>Let’s go into the root folder and create a folder named src, inside it, let’s create three other folders named:</p><ul><li>Model</li><li>Controller</li><li>Route</li></ul><p>Inside the Model folder, let’s create a file named model.user, Inside the controller, create a file named controller.user and inside the Routes folder, let’s create a file named route.user as shown below in the terminal:</p><pre>mkdir src</pre><pre>cd src</pre><pre>mkdir Model Controller Routes</pre><pre>cd Model</pre><pre>touch model.user.js _coreUser.js model.admin.js</pre><pre>cd ..</pre><pre>cd Controller</pre><pre>touch controller.user</pre><pre>cd ..</pre><pre>cd Routes</pre><pre>touch routes.user</pre><h3>Schema Design</h3><p>Before diving into the schema design, I will create a user and admin schema with first and last names in common. Let‘s go into the _coreUser file and add the following to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/0*jG-m1slgBGMiJtpo" /></figure><p>I imported the mongoose, accessed the schema property of the mongoose and created a base schema that holds the first and last name. Note that the _coreUser file holds the common properties that a user and an admin will share in common.</p><p>When using the mongoose discriminator, it allows us to add a key and a default collection name — optional as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/0*pR7-XGVY0Vu5j535" /></figure><p>So here, I declared a baseOption variable that holds an object with properties; discriminatoryKey, which is used as a unique key to differentiating the two schema — user/admin, the collection, that is used to override the added model name, and timeStamp, that is used to capture the created and updated time of the collection.</p><p>Let’s add the baseOption at the options argument of the schema as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/0*qmT9IJvIiKcxS2fY" /></figure><p>The BaseUserSchema design now looks like the snippet above. Finally, I will export the schema for other schemas to inherit from it as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/0*0YYrEAt2RLDp3jIz" /></figure><p>In the snippet above, I created communication between the schema and the MongoDB database and assign a schema name as baseUserSchema — it will be overridden with the collection property I set in the options variable above, and the schema itself as the second argument.</p><h3>Design The UserSchema</h3><p>Let’s go into the model.user file I created above and add the following to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/0*8GJMv4PywSf36qCe" /></figure><p>I created a schema that holds the other properties that a user should have, just like the baseSchema, the mongoose and schema were added to the same way.</p><p>So, to inherit the first name and last name that was created in the baseUser schema above, I will first show you what you may likely be seeing online. To demonstrate that, I will have to adjust the base schema a bit by removing the baseOption and passing in an object that holds only the timeStamp as shown below:</p><pre>{timeStamp: true}</pre><p>Inside the userSchema I will add a new schema property in it as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9yjEXIUecyD7TQG2" /></figure><p>In the snippet above, I am using the id used to save the user data in the database as a reference to the baseUserSchema, and set the model’s name of the schema I want to access its collection as the ref value.</p><p>So, the below happens when you use the ref method:</p><ul><li>Create a separate collection in the database,</li><li>Create the baseUser data first before other referenced properties</li><li>Have the full name as an objectId</li><li>It won’t be uniform</li></ul><p>The snippet above will get you the code snippet below:</p><pre>{</pre><pre>username:&quot;username&quot;,</pre><pre>phoneNumber: &quot;+2348169543479&quot;,</pre><pre>fullName: ObjectId(&quot;Id&quot;);</pre><pre>}</pre><p>Meanwhile, what you want may be something like the code snippet below:</p><pre>{</pre><pre>username:&quot;username&quot;,</pre><pre>phoneNumber: &quot;+2348169543479&quot;,</pre><pre>firstName: “princewill”,</pre><pre>lastName:”chime”</pre><pre>}</pre><p>So, I will continue by showing you how to inherit the baseschema properties rather than referencing them in the snippet below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/0*ecLlRK1O1TJ51naT" /></figure><p>Unlike the baseUser schema that I used the mongoose.model() method, I imported the BaseUserSchema, accessed the discriminator property that holds two arguments, the first one is the key used to save the user collection, the second one is the user’s properties, and finally, I exported the userSignup model for use in the controller’s functions i will be creating soon.</p><h3>Create The Admin Schema</h3><p>Inside the model.admin file I created earlier, let’s add the following code snippet into it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/0*4_R9qhyip0wC_wZH" /></figure><p>In the snippet above, the admins are set to have two different properties from the users’ schema. Like the user schema above, I set an admin text as a key to be used to reference admin collection in the database. The role and leavePeriod enum is declared above the schema as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8HXdJiBxOe_AfMOD" /></figure><p>The role holds the role of admins and the leavePeriod holds the months that are expected of an admin to be on leave.</p><h3>Create Of Controller</h3><p>Inside the controller.user file I created above, add the following code snippet into it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/0*lVJnx9QGMnK645R1" /></figure><p>I created the createUser function that handles a new instance of a user. To make sure that I am saving user data, I have to import the UserSignUp so that the baseschema will save the data into the collection of the users and not the admin collection.</p><p>The req.body holds what I will be passing to the req body of my HTTP request. I made a check to verify that req.body is not empty, I used the try and catch method to monitor the saving of data to the database against any error. If successful, I returned the created user object back to the client, if error, I returned the error message back to the client.</p><p>Still inside the controller.user file, let’s create the controller that will handle the creation of an admin as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/0*iJR4CNsM6IV2vUB6" /></figure><p>More like the previous code snippet, I imported the AdminSignUp instead of userSignUp.</p><h3>Creating Route</h3><p>Inside the route.user file I created above, let’s add the code snippet as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pADLaXkWFVy2155r" /></figure><p>I Imported both createUser and createAdmin controller from the controller.user file. The UserRouter holds a router object that I can use to reference any HTTP request method, I use the post method of the userRouter to create a pathway and executed the controller functions according to the paths and finally exported the UserRouter for use in the app file I created earlier.</p><p>So, inside the app file let’s adjust it with the code snippet below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*S_9ewXb1e_mgDx0x" /></figure><p>The code snippet above will enable me to watch for the user request on any of the assigned paths. app.use() method accepts two arguments, the first is a prefix to the API gateway while the second is the router methods.</p><h3>Making Request withIn VsCode</h3><p>Moving forward, I will be using an extension called:</p><pre>httpYac - Rest Clientv5.5.6</pre><pre>By Andreas Weber</pre><p>To get started with the extension, all it needs is to create a file with an http-extension(filename.http), and follow the <a href="https://marketplace.visualstudio.com/items?itemName=anweber.vscode-httpyac">guideline</a> to get started</p><p>Inside the file — request.http, let’s create a new user and a new admin as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/0*Ccd9qRVp9GUbzxbA" /></figure><p>HttpYac allows us to declare a global variable and use them as shown in the snippet above. I made a post request, set the headers and passed the global variables in the body of the request.</p><p>Let‘s take a look at how the data that was created looks in the code snippet below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*1UpOlzPbQsVx74c2" /></figure><p>Once the request is successful it saves the user data like the snippet above. Note that the firstName and lastName did not save as an ObjectId but as a property of the user collection.</p><p>Also, I talked about the discriminator key, which in my case I assign the user and admin model different keys, which are users, and admin. In the database, the two collections are saved as one user — the value assigned to the collection in the schema options model.</p><p>Notice also, that I have a new property added to the collection — “user”, it is the discriminator key that I assigned in the baseSchema model, this key will now hold as value; the model names of the different models.</p><p>In the code snippet below, let’s see how the structure of an admin collection looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/0*5wbt4qry_0Zv7VUf" /></figure><p>Unlike the user data structure, the added property — “user” is now admin — the name of the admin model. Because it’s the admin data, the role and leavePeriod are part of the data.</p><h3>Conclusion</h3><p>Finally, you could see the result of the API request I made. Going forward, I hope you will start writing your own server code using express.js, building a restful API, designing a schema structure, handling your request from the server, connecting an express server to your MongoDB database, and lastly, start using the mongoose discriminator to inherit properties and not using ref.</p><p>If this article was helpful to you, kindly like, comment, share and follow me on my <a href="https://www.linkedin.com/in/chime-princewill-3a2b1b192/">Linkedin</a> and <a href="https://princewillchime43.medium.com/">Medium</a> to see more of my article. Click the following link to access the <a href="https://github.com/chibuike07/mongoose-discriminator">source code</a>.</p><p>Feel free to drop any suggestions/comments. If you have a topic based on the Javascript/React.js ecosystem, kindly reach out and I’d be glad to write on it. Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c6e89c3795" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/mongoose-discriminator-an-easy-way-to-inherit-schema-properties-6c6e89c3795">Mongoose Discriminator: An easy way to inherit schema properties</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Infinite Scroll: More to the act!]]></title>
            <link>https://faun.pub/react-infinite-scroll-more-to-the-act-4b604b995b55?source=rss-ca30ca69cc7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b604b995b55</guid>
            <category><![CDATA[infinite-scroll]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Chime Princewill]]></dc:creator>
            <pubDate>Mon, 25 Jul 2022 10:53:46 GMT</pubDate>
            <atom:updated>2024-06-04T06:35:21.044Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xPdrhGbrC7MJgiQG" /></figure><h3>Introduction</h3><p>As a Frontend Engineer, the beauty of an application does not just rely on the looks, it also has a lot to do with flexible access to an application. Nowadays, uncountable data is fetched from the server/API and if not handled properly you may end up crashing an application.</p><p>Also, you may have been in a situation where you want to allow users to fetch their data seamlessly without having to let them click on a button before getting more batching of their data.</p><p>If you had wished to perform the above-mentioned and have a seamless flow of data while scrolling on the window, perform pagination from the frontend, use React-Query — use query hook to manage requests, and learn best practices, then this article is for you.</p><h3>Things to Learn</h3><p>In this article, I will be guiding you through how to do the following:</p><ul><li>Manage users’ data using ReactJs hooks,</li><li>How to use react-query, useQuery hook to handle requests,</li><li>Handle infinite scroll,</li><li>Handle pagination from the frontend,</li></ul><h3>Prerequisites:</h3><ul><li>Know Javascript</li><li>Know ReactJS Basic</li><li>Install Node/Npm</li></ul><h3>Setting Up Your Environment</h3><p>To create a new react project, use the following<a href="https://create-react-app.dev/docs/getting-started/"> <strong><em>link</em></strong></a>, and name it react-infinite-loop. In your terminal, let’s install axios and react-query as shown below:</p><pre>cd Desktop</pre><pre>cd react-infinite-loop</pre><pre>npm i react-query -save</pre><pre>npm i -D axios -save</pre><pre>code .</pre><p>In the snippet above, I went into the desktop folder, navigated to the project I created, and installed two dependencies,<a href="https://faun.pub/api-calls-using-react-query-hooks-abbfff16b40e"> <strong>react-query</strong></a> which is a hook that helps me manage HTTP requests, a library, axios for making a request and finally opened the project in vscode with the code dot(.).</p><h3>Initializing React Query</h3><p>Let’s go into the app component and add the following as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/0*PB-gOc4Nbzdo3iEG" /></figure><p>In the snippet above, an instance of the client was created, assigned to the client variable, and later passed into the client parameter of the QueryClientProvider to enable all the wrapped components to have access to the client.</p><h3>Create Folder Structure</h3><p>Let’s go to the terminal and run the following:</p><pre>cd  src</pre><pre>mkdir Component Query View</pre><pre>cd Component</pre><pre>touch List.jsx</pre><pre>cd ..</pre><pre>cd View</pre><pre>touch Home.js</pre><p>In the snippet above, I went into the src folder and created three different folders named Component, View, and Query. I created two files, List.jsx which is inside the component folder, and the Home.js file which is inside the View folder.</p><h3>Request Handler</h3><p>Inside the Query folder, I created above, create a file and name it util.js, inside it add the following code snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*SrB-1ShTGwGcHmgm" /></figure><p>In the snippet above, I created a fetchPost function that will handle the fetching of posts from an <a href="https://jsonplaceholder.typicode.com/posts">API</a>, a search query of page and limit was passed along with the request in other to limit the amount of data that will be fetched at once from the API and I also set the Content-Type of the request to application/json and set the encoding format to UTF-8.</p><p>The page and limit are parameters that will be passed from where I will be executing the fetchPost function. So because I will be using the <a href="https://faun.pub/api-calls-using-react-query-hooks-abbfff16b40e">useQuery</a> hook as my API manager, I destructured the queryKey property. The queryKey property will be an array that has two properties, a key for the request and other options(page/limit).</p><p>Because I only needed the options, I had to use the comma to split out the key to the request and then destructured the page and limit. You can read more on react-query(useQuery) <a href="https://faun.pub/api-calls-using-react-query-hooks-abbfff16b40e"><strong><em>here</em></strong></a>.</p><h3>Fetch Request Using UseQuery Hook</h3><p>Let’s go into the Home component I created above and add the following to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/0*-8BRU4kEWDw3WZYd" /></figure><p>Previously, I imported the Home component into the app component that has not been created, inside it, I created a default state that will handle the page, limit, and the posts that will be fetched. For now, I am returning a text.</p><p>Let’s move on to fetch the posts onMount of the page using the <a href="https://faun.pub/api-calls-using-react-query-hooks-abbfff16b40e">useQuery</a> hook from react-query as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*jpTvcdfbcvOTnp6q" /></figure><p>In the snippet above, I used the <a href="https://faun.pub/api-calls-using-react-query-hooks-abbfff16b40e">useQuery</a> hook to manage the post request once the Home component is mounted, I imported the fetchPost function that handles API calls as a parameter to the <a href="https://faun.pub/api-calls-using-react-query-hooks-abbfff16b40e">useQuery</a> and passed an array that holds the request queryKey and other options (page and limit).</p><p>I used the retry property to rerun the request if failed initially, I set the delay to three seconds before retrying the request and avoided making a request to the API on every focus on the window. <a href="https://faun.pub/api-calls-using-react-query-hooks-abbfff16b40e">UseQuery</a> hook gives us an onError and onSuccess properties that manage the error and success response of the request. So once the request is successful, I set the returned data to the post-state I created above.</p><h3>Render Fetched Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/0*FKXEME-OkruWe1Nb" /></figure><p>In the snippet above, When the Home component is mounted, I used a conditional rendering to check if posts were returned from the HTTP request I made by checking if the length of the post-state is greater than zero.</p><p>Once it is greater than zero, I loop through the post array and destructure the post properties that will be displayed to the users and pass them as a prop to the List Component I created earlier.</p><p>Remember, I destructured the isFetching and isLoading from the <a href="https://faun.pub/api-calls-using-react-query-hooks-abbfff16b40e">useQuery</a> Hook, those are used as a flag to monitor when a request is trying to fetch some data and when it’s updating the cached data with the recent change in the data.</p><p>Let’s add the below code snippet to manage what happens while I wait for my request to be completed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*bKorFchQd6JUqGfD" /></figure><p>Just after the rendering of posts, add the snippet above to show the user that the post is yet to be fetched.</p><p>Let’s go into the List component and render the props as expected as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*UIk4h53leOC-gvxm" /></figure><p>I destructured the props and rendered them in their respective elements. Let’s go into the browser and take a look at what I have done so far in the snippet below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SUjJuKsBeE1lcKXj" /></figure><p>In the snippet above, I have successfully rendered the fetched posts to the browser, the title, userId, and the body of the posts. Now that the post is rendered, let’s look at how to load more posts once I reach the end of every page fetched.</p><h3>Infinite Scroll (Pagination on Scroll)</h3><p>For us to be able to fetch the next page of the data on scroll, there are checks I need to set in place, these checks are as follows:</p><ul><li>Get when the user scrolls to the bottom,</li><li>Set a flag,</li><li>Add the next page data to the previous fetched</li></ul><p><strong>Get when the user scrolls to the bottom</strong></p><p>Inside the Home component, let’s add the following code snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*9k9tMDkUtSE4Kfqj" /></figure><p>In the snippet above, I used a hook called <a href="https://reactjs.org/docs/hooks-reference.html#uselayouteffect">useLayoutEffect</a>, this hook is imported from the react library, it is useful when you want to read the layout from the DOM and synchronously re-render.</p><p>ScrollTop; is used to get the height of the document on scroll starting from zero, scrollHeight; is used to get the browser height, and clientHeight: is used to get the visible height of the document, all were gotten from the document body, and lastly I passed the handleScroll function to the event listener to execute anytime the user scrolls.</p><p>Inside the handleScroll method, just after the declarations add the following code snippet:</p><p><strong>Set a flag</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*7-EVXZwSfyYsBQuk" /></figure><p>Above, I minus the total current height of the document(scrollTop) from the total height of the document(scrollHeight) and check if it’s equal to the visible height of the document(clientHeight) on the d scroll and assigned the value to the setPaginateFlag — a boolean value.</p><p>Afterwards, I checked if the user has reached the bottom of the visible height, if it’s true, I set a flag to a state called setMorePosts, if morePosts is true and there is more data to fetch, then I fetch the next data.</p><p>Previously the useLayoutEffect is set to execute onMount, but I also want it to rerun when the morePosts and nextPage are updated, so let’s set the morePosts and nextPage in the useLayoutEffect dependency array as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*OL8oGKiJR2stC7RJ" /></figure><p>The setMorePosts and the setNextPage state are declared above the <a href="https://faun.pub/api-calls-using-react-query-hooks-abbfff16b40e">useQuery</a> function as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*4xysOGjfixhr_21X" /></figure><h3>Handle Pagination</h3><p>Most frontend engineers prefer pagination to be handled by the backend engineers. I am using fake data from <a href="https://jsonplaceholder.typicode.com/posts">JsonPlaceholder</a> so let’s handle the total page and the next page of the data in the following code snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*ZM3pOkj-xtthPZNL" /></figure><p>By default, the total data from the API is one hundred (100). I divide the total number of data by the amount of data per page to get the totalPage. I checked if the totalPage is greater than the current page.</p><p>If yes, I increase the page by 1 which gets the next page, else, I return the current page and finally set the nextPage to the nextPage variable — this happens each time the request is successful. The limit variable becomes one if I set it to hold a value that is less than one.</p><p>It should be noted that for uncountable data you may have to fetch all and then write the above algorithm for pagination or rather have the total count sent to you by the backend engineer.</p><p><strong>Add the next page data to the previous fetched</strong></p><p>Next, I will have to merge the next page data to the current data as shown in the following snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/0*gpOl7zGsSB2g06G4" /></figure><p>In the snippet above, I adjusted the setPosts function and used a spread operator to concatenate the current posts and the next batch of posts fetched from the request.</p><h3>The demo</h3><p>I guess is time to take a look at what I have done so far using the following <a href="https://res.cloudinary.com/hobbyluv07/video/upload/v1657610139/infinite_scroll_wia5fa.mp4">demo link</a>.</p><h3>Conclusion</h3><p>Finally, from the demo above, it’s obvious that the infinite Scroll is working seamlessly. I believe from now you should stop using third-party observers, use <a href="https://faun.pub/api-calls-using-react-query-hooks-abbfff16b40e">useQuery</a> to fetch data from an API, handle pagination from the frontend, handle batching of data and finally allow users to fetch more of their data without clicking a button preferably on scroll on the window.</p><p>If this article was helpful to you, Kindly like, comment and follow me on <a href="https://www.linkedin.com/in/chime-princewill-3a2b1b192/">Linkedin</a> and <a href="https://princewillchime43.medium.com/">Medium</a> to see more of my article. Click on the following link to access the source <a href="https://github.com/chibuike07/react-infinite-scroll"><strong><em>code</em></strong></a>.</p><p>Feel free to drop any suggestions/comments. if you have a topic based on the Javascript/React.js ecosystem, kindly reach out and I’d be glad to write on it. Thanks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*L9IROemSq6EgoVJu.png" /></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀Developers: Learn and grow by keeping up with what matters, <a href="https://faun.to/8zxxd">JOIN FAUN.</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b604b995b55" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/react-infinite-scroll-more-to-the-act-4b604b995b55">React Infinite Scroll: More to the act!</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seamless Search using React Hook]]></title>
            <link>https://javascript.plainenglish.io/seamless-search-using-react-hook-539550664a9d?source=rss-ca30ca69cc7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/539550664a9d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Chime Princewill]]></dc:creator>
            <pubDate>Fri, 24 Dec 2021 12:07:18 GMT</pubDate>
            <atom:updated>2022-01-07T14:25:28.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ziVZX4pZZkLgiXCL" /><figcaption>Photo by <a href="https://unsplash.com/@xps?utm_source=medium&amp;utm_medium=referral">XPS</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Nowadays, You can barely see an application(mobile/web) that will not create a section where users can search through an item from a large collection of items. In most cases, I have seen developers trying to implement such in their application but ended up getting just a value back instead of getting all the items that include the search. A typical example of this has been implemented using <a href="https://medium.com/nerd-for-tech/seamless-search-with-vanilla-javascript-e447c440ef59"><strong><em>vanilla JavaScript</em></strong></a><strong><em>.</em></strong></p><p>In this article, I will be implementing this same behavior using <strong>React Hook. </strong>I will be using Visual Studio Code for my code editor.</p><p><strong><em>Prerequisites</em></strong></p><ul><li>Install Node.js and npm</li><li>Knowledge of JavaScript</li><li>Basics of React</li></ul><p>Follow the <a href="https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started"><strong><em>link</em></strong></a><strong><em> </em></strong>to create a react project named <strong>seamless_search_react</strong></p><p>Let’s go into the src folder and create some folders and files as shown below in the terminal:</p><pre>cd src</pre><pre>mkdir Component Util View context reducer</pre><pre>cd Component</pre><pre>touch CustomUser.js SearchBar.js Users.js</pre><pre>cd View </pre><pre>touch Home.js</pre><pre>cd Util </pre><pre>touch userCollection.js </pre><pre>cd context </pre><pre>touch SearchContext.js</pre><pre>cd reducer</pre><pre>touch actionjs reducer.js</pre><p>Inside the userCollection.js, let’s use the following <a href="https://jsonplaceholder.typicode.com/users"><strong><em>link</em></strong></a> to get the dummy user data that will be used for this article. Copy it and paste it inside the file mentioned above.</p><p>Going forward, I will be using react <strong>useContext </strong>and <strong>useReducer </strong>for my state management. Inside the SearchContext component, let’s create a context as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*f28UrlJ3w6dvXMEJgyBjnQ.png" /><figcaption>create a context</figcaption></figure><p>In the above snippet, I assigned the new context to the SearchContext variable and exported it for use in other components. I set the default value of it to an array — it accepts an object as well. Inside the array, it holds two properties, which are an empty object and a function.</p><p>Let’s create a provider function that will handle the state and reducer as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*ZTWFp9OG-1Lwuj2fQZGt3A.png" /><figcaption>provider function</figcaption></figure><p>You can refer to this function as a mother that provides food for its children. It makes the state and function available to all nested components that it wraps.</p><p>I used the <strong>useReducer </strong>hooks function as my <strong><em>state</em></strong>, just like the useState hook. It takes up to three-argument but only two will be used in this article. The first one is:</p><ul><li>A reducer function, and</li><li>A state</li></ul><p>The reducer function was imported from the reducer file that was created earlier while the state was initialized right after the reducer function. For now, I only have an object that holds a query property which is a string.</p><p>Lastly, I return the provider property of the SearchContext and pass the state and the dispatch function to the value props of it; to be accessed by other children.</p><p>Let’s go into the reducer file and add the following into it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*guo0pLrFlBd0I0jCAk2JKQ.png" /><figcaption>reducer function</figcaption></figure><p>In the above snippet, if you could remember, I passed the reducer function into the useReducer hook function; it passes two arguments to the reducer function:</p><ul><li>state and,</li><li>action</li></ul><p>The <strong>state</strong> is the current data of the reducer, and the <strong>action</strong> is a dispatch function that holds a <strong>type</strong> and <strong>payload </strong>property<strong>. </strong>The <strong><em>type</em></strong> is passed to the switch to watch out for the state that needs update and the <strong><em>payload </em></strong>holds the data that will update the state.</p><p>The <strong>t</strong> variable there is an import that will be holding all the <strong><em>action </em></strong>types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*JbBOk_F1hK9tW_X3BOQJEw.png" /><figcaption>importing action type as t</figcaption></figure><p>Let’s go into the action file I created earlier and add the following into it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*tpxdrec1WnW8O4dpQyQTvA.png" /><figcaption>action types</figcaption></figure><p>Now that I am done setting up the state management for the seamless search, I will import the provider component I defined above into the app component and nest the Parent component(Home) into it as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*xA929ATAtkUD06Y5PVs7aw.png" /><figcaption>context provider</figcaption></figure><p>In the above snippet, I wrapped the Home component with the context provider function to make all of my context — state, available to the wrapped components.</p><p>Going forward, I can now have access to the global state from anywhere in the wrapped components.</p><p>Let’s go into the users component and import the usercollection data to have it rendered on the page as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*A8jEbINq40g7WJIdbWejyQ.png" /><figcaption>render users</figcaption></figure><p>The users were imported from the util file I created earlier, I made a check to verify that the usercollection isn’t an empty array, hence, I looped through it and destructured the properties I want to render to the browser; those properties were passed as props to the customUser.</p><p>Let’s go into the customUser component to render the individual user data to an element as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*CGBwiPCuSUTw-RPD3ZEAcg.png" /><figcaption>custom user</figcaption></figure><p>Let’s take a look at the progress so far with the following <a href="https://res.cloudinary.com/hobbyluv07/video/upload/v1640245996/React_App_-_Google_Chrome_2021-12-23_09-47-43_a36vsv.mp4"><strong><em>demo</em></strong></a><strong><em>.</em></strong></p><p>The user data has been successfully rendered to the browser as you see in the above demo.</p><p>Let’s go into the SearchBar component and create a form field to handle the search query as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*vFRbagh3e31X6p0YWD0TJw.png" /><figcaption>search bar component</figcaption></figure><p>In the above snippet, an input field was rendered into the form element, the handleQuery function — will be added shortly, is an onChange function that updates the state when there is a change in the input field. Let’s define the handleQuery function as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*o8Sw3eReMsepKQJifBmvmQ.png" /></figure><p>In the above snippet, I used the useContext hook to access the context and destructured the state and a function that sets the state. In the handleQuery function, I prevented the default behavior of a form—returning void, and in turn, set the current input value to the global state.</p><p>Now that I am done creating the SearchBar component, let’s go into the util file and add a function that will handle the filtering of the items I searched as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*fCUYFfMdfNiH-TeOF5Fwdw.png" /><figcaption>search middleware</figcaption></figure><p>In the above snippet, I looped through the users and returned the user’s name(lowercase) that match the search value(lowercase).</p><p>Let’s go into the users component and adjust it a little bit as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*-qAPCE7C37yBB6PeTkKvyA.png" /></figure><p>In the above snippet, remember the filtersearch function was exported from the util file, instead of looping through the usercollection data directly, I am looping into the returned data of the filterSearch function. The userCollections and <strong><em>query </em></strong>were passed as an argument to the filterSearch function for adequate checking.</p><p>Now that we have all implemented these, let us see what we have built in the following <a href="https://res.cloudinary.com/hobbyluv07/video/upload/v1640253402/seamless_video_fqkgbu.mp4"><strong><em>Demo</em></strong></a><strong><em>. </em></strong>The source code is available <a href="https://github.com/chibuike07/seamless_search_reactjs"><strong><em>here</em></strong></a><strong>.</strong></p><p>Finally, we have gotten to the end of this article, and I hope you can integrate a seamless search process going forward in your react application.</p><p>If this article was helpful to you don’t forget to hit the clap icon, share the article and follow me on my <a href="https://princewillchime43.medium.com/"><strong><em>Medium</em></strong></a>, and <a href="https://www.linkedin.com/in/chime-princewill-3a2b1b192/"><strong><em>Linkedin</em></strong></a> to see more of my articles.</p><p>Kindly drop any suggestions. If you have a topic based on the JavaScript/React ecosystem, feel free to reach out and I’d be glad to write on it. Thanks.</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><em>free weekly newsletter</em></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><em>community Discord</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=539550664a9d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/seamless-search-using-react-hook-539550664a9d">Seamless Search using React Hook</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Calls Using React-Query Hooks]]></title>
            <link>https://faun.pub/api-calls-using-react-query-hooks-abbfff16b40e?source=rss-ca30ca69cc7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/abbfff16b40e</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Chime Princewill]]></dc:creator>
            <pubDate>Mon, 25 Oct 2021 16:25:39 GMT</pubDate>
            <atom:updated>2024-06-04T06:35:45.731Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9yBqMBbAGx-ue-Wi" /><figcaption>Photo by <a href="https://unsplash.com/@ejuneolgac?utm_source=medium&amp;utm_medium=referral">June O</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When building an application(mobile/web) you will most likely want to get some data from an API or locally with static JSON files. For a technology like javascript and its libraries, it has an inbuilt method like Fetch and a library like Axios which helps to make API calls.</p><p>Libraries like ReactJs with their life cycle methods make it more efficient to make an API call. In some scenarios, you may want to update the state only when there is an update in the data and not always onMount or onUpdate in the components.</p><p><strong>Prerequisite:</strong></p><ul><li>Node and Npm installed</li><li>Know javascript</li><li>Know ReactJs</li></ul><p>In this article, I will show you how I manage my requests with a library called <strong><em>React-Query; </em></strong>It comes with a lot of hooks that help me to handle requests without thinking of the following edge cases:</p><ul><li>Reflecting updates to data</li><li>Performance optimization</li><li>Updating “out of date” data in the background</li><li>Caching</li><li>Managing memory and garbage collection of server state and more.</li></ul><p>I am using visual studio code for this article. So if you are with me, let’s get started.</p><p>To start a react project use this <a href="https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started#initializing_your_app"><strong><em>link</em></strong></a><strong><em> </em></strong>to create a project named reactquery.</p><p>Let’s install the react-query library and Axios in the following snippet:</p><pre>yarn add react-query</pre><pre>yarn -D add axios</pre><pre>code .</pre><p>The above code snippet is all we need to get started. Inside the react-query project that was created above, I installed the react-query package, installed Axios into the devDependencies, and open the directory in the vscode.</p><p>Inside the src folder, let’s create the</p><p>two directories and some files as follows in the terminal:</p><pre>cd src </pre><pre>mkdir component view</pre><pre>cd component </pre><pre>mkdir query posts</pre><p>Let’s integrate the react-query to have access to the client in all the components like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*2KRxH9aE1fYtUjrfetTpRQ.png" /><figcaption>connecting react-query</figcaption></figure><p>In the above snippet, I assigned an instance of QueryClient to the client variable and later pass it as a prop to the provider that is wrapping all of the components, the client is made available to all the components that are wrapped.</p><p>Inside the query directory, let’s create a file named posts.js and add the following into it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*ugPG6RV0pE9Q9td5NFj62Q.png" /><figcaption>API request</figcaption></figure><p>This is an async function that awaits the data that is returned from the API call. The function is exported for use. Shortly, I will show you where I will be importing the <strong>fetchPost</strong> function.</p><p>Inside the posts directory let’s create a component named posts.jsx and add the following into it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*xXNddcVStf78Fg8C1N7yGA.png" /><figcaption>manage request</figcaption></figure><p>In the snippet above, I imported useQuery from the react-query library and <strong>fetchPosts</strong> from the posts.js file. The fetchPosts is a function that handles the API call in the background while the useQuery is a hook that helps to manage the request.</p><p>useQuery needs a query key and an async function for it to manage a request. The query key can be a string or an array, the second argument is where the function that makes the request is been passed. Once you have passed all the required arguments, it returns a series of variables to use. In my case, I destructured: <strong>data</strong>, <strong>isFetching</strong>, and <strong>isLoading</strong> from all that was returned.</p><p><strong><em>Data</em></strong> holds the response data if the request is successful, <strong><em>isFetching </em></strong>is<strong><em> </em></strong>called<strong><em> </em></strong>when<strong><em> </em></strong>there<strong><em> </em></strong>is an update in the data, <strong>isLoading </strong>works similarly to <strong>isfetching</strong>, except that it is called when it’s trying to get the data. while <strong>isfetching</strong> is called when there is an update in the data.</p><p>In the following code snippet, let’s render the returned data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*dvgb5krCDj1t8tMmKCxrrA.png" /><figcaption>render posts</figcaption></figure><p>In the above snippet, I am displaying some text when data is loading, another when fetching updated data and lastly render the data to the browser. This method of rendering data is likely What you may be seeing often in people’s codebase.</p><p>For me, I like handling the data as I want, like, setting data to the state, handling more things when the request returns some data or an error. So to that, I will show you how I manage the data that comes back and more in the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*RLghEXUu-3jIJkCCJnIElA.png" /><figcaption>managing data</figcaption></figure><p>I created a state using useState-hook, useQuery gives us a third argument that holds options to manage the request properly. Common options are OnError and OnSuccess that I used in the snippet above.</p><p>OnError returns the error that is associated with the request, and onSuccess returns the data once the request is successful. When data is returned, the data is set to the state; instead of mapping the data directly like earlier, I am now getting the data from the state.</p><p>Note: Inside the OnSuccess | onError, you can decide to handle more functions/variables.</p><p><strong>How to pass a query/params to a useQuery:<br></strong>To pass a query to the useQuery function I will add the query/params as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*XjR-YBv4kaSALidi-a72nQ.png" /><figcaption>query</figcaption></figure><p>Inside the Post component, I adjusted the query key and pass in an object that holds the limit of posts that will be returned. Let’s go to the posts file in the query directory and adjust it with the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*bkvVlXEoiIFjxtaq-nG_uA.png" /><figcaption>get passed query</figcaption></figure><p>In the above snippet, I destructured the query key from the props, remember, the query was wrapped in an array that holds the key and the data limit, the limit is inside an object, so I destructured the limit from the object in other to use it in the request.</p><p>When making an API call with useQuery, once the query fails it tries to refetch the query up till three-time before it throws an error but it can be limited using the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*gYW8YohA5Q4XU1IQ1T0BAA.png" /></figure><p>The <strong><em>retry</em></strong> specifies the number of times the request should be called, so after the initial call, if there is any error, it tries to make the request one more time. On the other hand, once there is an error, it refetches immediately. So to avoid that, I added the <strong><em>retryDelay</em></strong> to wait for three seconds before retrying the request.</p><p>useQuery tries to fetch the data on every focus on the window, so to stop that behavior I set the <strong><em>refetchOnWindowFocus</em></strong> to false.</p><p>In some cases, you may want to condition the query — something happens before the query is made. you will have to add the enabled option and set it as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*cfFNtcP8QIEPPpqqIN6LRg.png" /><figcaption>condition</figcaption></figure><p>The condition that is passed to the enabled is a state variable, when set to false the query returns, else the query will make a call to the API.</p><p>At times, you may wish to add multiple dependencies, to do that, you will have to condition the query as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*0UR5jRhmLfdkwtpUWZuGHA.png" /><figcaption>dependency</figcaption></figure><p>The above snippet is used whenever you want to set multiple conditions to a query, it is like an observer that observes when there is a change to any of the dependencies — just like the way dependencies are set in the useEffect dependency array.</p><p>There are some cases, where you would want to <strong>refetch</strong> a query when something happens; to do that, you will destructure the <strong>refetch</strong> method from useQuery as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*hQAAKQDXScUvgdQe3NCQpQ.png" /><figcaption>refetch a query</figcaption></figure><p>The <strong>refetch</strong> is a method that refetches a query once it&#39;s been called in any function or event triggers.</p><p>Now that we have all implemented these, let us see what we have built in the following <a href="https://res.cloudinary.com/hobbyluv07/video/upload/v1634837753/Screencast_from_21-10-2021_18_33_37_cf9fpb.webm"><strong><em>Demo</em></strong></a><strong><em>. </em></strong>The source code is available <a href="https://github.com/chibuike07/react-query-tutorial"><strong><em>here</em></strong></a><strong>.</strong></p><p>Finally, we have gotten to the end of this article, and I hope you will start using react-query going forward to manage your API calls.</p><p>If this article was helpful to you don’t forget to hit the clap icon, share the article and follow me on my <a href="https://princewillchime43.medium.com/"><strong><em>Medium</em></strong></a>, and <a href="https://www.linkedin.com/in/chime-princewill-3a2b1b192/"><strong><em>Linkedin</em></strong></a> to see more of my articles.</p><p>Kindly drop any suggestions. If you have a topic based on the JavaScript/React.js ecosystem, feel free to reach out and I’d be glad to write on it. Thanks.</p><figure><a href="https://faun.to/bP1m5"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCiLLad3dvZLwBa-B5cAVQ.png" /></a></figure><p>Join FAUN: <a href="https://faun.to/i9Pt9"><strong>Website</strong></a><strong> </strong>💻<strong>|</strong><a href="https://faun.dev/podcast"><strong>Podcast</strong></a><strong> </strong>🎙️<strong>|</strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong>|</strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong>|</strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷|<a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>🗣️<strong>|</strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin Group</strong></a><strong> </strong>💬<strong>|</strong> <a href="https://faun.dev/chat"><strong>Slack</strong></a> 📱<strong>|</strong><a href="https://thechief.io/"><strong>Cloud Native</strong> <strong>News</strong></a><strong> </strong>📰<strong>|</strong><a href="https://linktr.ee/faun.dev/"><strong>More</strong></a><strong>.</strong></p><p><strong>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abbfff16b40e" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/api-calls-using-react-query-hooks-abbfff16b40e">API Calls Using React-Query Hooks</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>