<?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 Viany Noubissi on Medium]]></title>
        <description><![CDATA[Stories by Viany Noubissi on Medium]]></description>
        <link>https://medium.com/@g696607013?source=rss-3a812241d63e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uLe6cyRYrau08E0ymiXh7g.jpeg</url>
            <title>Stories by Viany Noubissi on Medium</title>
            <link>https://medium.com/@g696607013?source=rss-3a812241d63e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:13:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@g696607013/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[Full-Stack App Tutorial using Next. JS, TypeScript and Firebase Database]]></title>
            <link>https://medium.com/@g696607013/full-stack-app-tutorial-using-next-js-typescript-and-firebase-database-c706214fe694?source=rss-3a812241d63e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c706214fe694</guid>
            <dc:creator><![CDATA[Viany Noubissi]]></dc:creator>
            <pubDate>Mon, 21 Aug 2023 16:32:40 GMT</pubDate>
            <atom:updated>2023-08-21T16:32:40.491Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*plc9aAfNa9nRcnmVZi-Dpw.png" /><figcaption>Full-Stack app with Nextjs, TypeScript and Firebase</figcaption></figure><p>Hey, devs, welcome to this tutorial; we will build a full-stack App with Next.js, Typescript and Firebase.</p><h3><strong>Prerequisites</strong></h3><p>Before we start writing code, you need:</p><ul><li><a href="https://nodejs.org/en/">Node.js</a> installed on your computer.</li><li>Some basic knowledge of HTML, CSS, and JavaScript fundamentals.</li><li>Some prior knowledge of working with <a href="https://reactjs.org/">React</a>, <a href="https://nextjs.org/">Next.js</a>, and <a href="https://www.typescriptlang.org/">TypeScript</a>.</li></ul><h3><strong>Setting up TypeScript</strong></h3><p>We are using TypeScript to build our full-stack application. Next.js is bundled with TypeScript.</p><p>TypeScript comes with additional features that make your code minimalistic. These features include static typing, type notation, type checking, etc. Check this guide to compare and contrast TypeScript and Javascript</p><p>To use TypeScript, you’ll need to install the TypeScript JavaScript library. This will make TypeScript accessible to our project.</p><p>Next.js provides a TypeScript-first development experience for building your React application. It comes with built-in TypeScript support for automatically installing the necessary packages and configuring the proper settings. Running <strong><em>npx create-next-app@latest</em> </strong>will automatically add TypeScript and <strong><em>@types/react </em></strong><em>to our</em><strong><em> </em></strong>Next.js project</p><p>Note that Next.js is a React.js framework. So while using TypeScript, we need React type definitions. <strong><em>@types/</em></strong> provides TypeScript features to third-party frameworks such as React.</p><h3><strong>Creating a Firebase Project</strong></h3><p>To setup Firebase, use the following steps:</p><p>First, go to the <a href="https://console.firebase.google.com/">Firebase console</a> and <em>Add project</em>. Enter the preferred name of your project, i.e., <strong><em>next-js-todos-app</em></strong>. Then click continue</p><p>Create a project and give it some time to complete the process. When the project is ready, click <strong><em>Continue</em></strong>.</p><h3><strong>Adding a Firebase app</strong></h3><p>The next step is to create a Firebase app. We can implement this functionality using the code below:</p><p>On the newly created project page, click the web icon (<strong>&lt;/&gt;</strong>).</p><p>Enter your preferred app name, i.e., <strong><em>next-js-todos-app</em></strong>. Then click <strong><em>Register app</em></strong> and <strong><em>Continue to console</em></strong>.</p><p>In the next step, we will set up <strong>Firestore</strong>.</p><h3><strong>Setting up Firestore</strong></h3><p>To set up Firestore, follow the steps below:</p><p>In the Firebase App, navigate to the left menu, under <strong><em>build</em></strong>, and click <strong><em>Firestore Database</em></strong> then <strong><em>Create database</em></strong>.</p><p>Since we are not building a production application, select the <em>start in test mode</em> and move to the <em>Next</em> step.</p><p>Choose the Cloud Firestore location from the list of options available and then click <em>Enable</em> to set the selected location.</p><p>In the next step, we will set up our Next.js application.</p><h3><strong>Setting up Next.JS app</strong></h3><p>To set up our Next.js application, we will use <strong><em>create-next-app@latest</em></strong>.</p><p>To set it up, we will follow these steps:</p><p>Create a folder where you want the project to reside.</p><pre>cd ./your-project-folder-path</pre><p>Run the following command to bootstrap the Next.js application with TypeScript:</p><pre>npx create-next-app@latest full-stack-app</pre><p>The above command will create the Next.js application inside the <strong><em>full-stack-app</em></strong> folder.</p><p>Since we will be working with Firebase, the next step is to install the Firebase package. This will add the Firebase SDK to the Next.js project. Change the directory and make sure your command line points to the <strong><em>full-stack-app </em></strong>folder.</p><p>Then run this command to get the Firebase JavaScript library installed:</p><pre>npm install firebase</pre><p>With Firebase installed, run the following command to start the development server:</p><pre>npm run dev</pre><p>In your browser, navigate to http://localhost:3000. You should be able to view the following default Next.js landing page:</p><p>Let’s start by integrating Firebase and adding TypeScript.</p><h3><strong>Initializing Firebase app</strong></h3><p>The next step will be to initialize the Firebase database in the Next.js app.</p><p>In simple terms, initializing a Firebase app means connecting the Firebase database instance/SDK so that we can work and scale the Next.js application.</p><p>This simply involves collecting the Firebase credentials that are specific to our Firebase application.</p><p>To initialize it, we will use the following steps:</p><p>Create an <strong><em>.env.local</em></strong> file in your project root folder. This will host the environmental variables.</p><p>In your Firebase dashboard, navigate to the <em>project settings</em>. Scroll down to <em>your apps</em> section and then to the <em>SDK setup and configuration</em>.</p><p>In the app settings, we will take the <strong><em>firebaseConfig</em></strong> object. Extract its contents to the <strong><em>.env.local</em></strong> file, as demonstrated below:</p><pre>NEXT_PUBLIC_FIREBASE_API_KEY = &quot;your_api_key&quot;<br>NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN = &quot;your_auth_domain&quot;<br>NEXT_PUBLIC_FIREBASE_PROJECT_ID = &quot;your_project_id&quot;<br>NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET = &quot;your_storage_bucket&quot;<br>NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID = &quot;your_messaging_sender_id&quot;<br>NEXT_PUBLIC_FIREBASE_APP_ID = &quot;your_app_id&quot;<br>NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID = &quot;your_measurement_id&quot;</pre><p>Replace every environment with the credentials listed in the <strong><em>firebaseConfig</em></strong> object.</p><p>Next, create a new <strong><em>firebase </em></strong>directory inside the project root folder.</p><p>Inside the <strong><em>firebase</em></strong> folder, create a file <strong><em>clientApp.ts</em></strong>.</p><p>We will configure the Firebase instance in the <strong><em>clientApp.ts</em></strong> file, as demonstrated below:</p><p>Start by importing <strong><em>initializeApp</em></strong> from the Firebase package.</p><pre>import {initializeApp} from &quot;firebase/app&quot;;</pre><p>Call the <strong><em>initializeAp</em></strong> function and pass in your credentials as listed in the <strong><em>env.local</em></strong> file:</p><pre>initializeApp( {<br>   apiKey:process.env.NEXT_PUBLIC_FIREBASE_API_KEY,<br>   authDomain:process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,<br>   projectId:process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,<br>   storageBucket:process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,<br>   messagingSenderId:process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,<br>   appId:process.env.NEXT_PUBLIC_FIREBASE_APP_ID,<br>   measurementId:process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID<br>});</pre><p>Import <strong><em>getFirestore</em></strong> from firebase.</p><pre>import {getFirestore} from &quot;firebase/firestore&quot;;</pre><p>Create a <strong><em>firestore</em></strong> instance.</p><pre>const firestore = getFirestore();</pre><p>Export firestore so that it can be accessible by the files that we will create later in this project.</p><pre>export {firestore};</pre><p>Since we have environmental variables, we will have to restart the development server.</p><p>Press <strong><em>ctrl + c </em></strong>to close it, and then <strong><em>npm-run-dev</em></strong> to start it.</p><h3><strong>Querying documents from Firestore</strong></h3><p>To query documents from Firestore, we will work on <strong><em>pages/index.tsx</em></strong>:</p><pre>import type { NextPage } from &#39;next&#39;<br>import Head from &#39;next/head&#39;<br>import styles from &#39;../styles/Home.module.css&#39;<br>const Home: NextPage = () =&gt; {<br>return (<br>   &lt;div className={styles.container}&gt;<br>   &lt;main className={styles.main}&gt;<br>     &lt;h1 className={styles.title}&gt;<br>     Todos app<br>     &lt;/h1&gt;<br>   &lt;/main&gt;<br>   &lt;/div&gt;<br>)<br>}<br>export default Home</pre><p>The above is just a skeleton of where we will start working on this todos app.</p><p>We have changed the <strong><em>pages/index.tsx</em></strong>, which means the existing linked CSS code won’t work on the newly added code.</p><p>Edit <strong><em>styles/Home.module.css</em></strong> file as follows:</p><pre>.container {<br>  margin-top: 50px;<br>  display: flex;<br>  flex-direction: column;<br>  justify-content: center;<br>  align-items: center;<br>}<br><br>.main {<br>  padding: 10px;<br>  margin: auto;<br>  flex: 1;<br>  display: flex;<br>  flex-direction: column;<br>  align-items: center;<br>  width: 50rem;<br>}<br><br>.footer {<br>  width: 100%;<br>  height: 100px;<br>  border-top: 1px solid #eaeaea;<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>}<br><br>.footer a {<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>  flex-grow: 1;<br>}<br><br>.title a {<br>  color: #0070f3;<br>  text-decoration: none;<br>}<br><br>.title a:hover,<br>.title a:focus,<br>.title a:active {<br>  text-decoration: underline;<br>}<br><br>.title {<br>  margin: 0;<br>  line-height: 1.15;<br>  font-size: 1.5rem;<br>  background-color: rgba(119, 8, 133, 0.644);<br>  padding: 10px;<br>  width: 50%;<br>  color: white;<br>  font-weight: bold;<br>}<br><br>.title,<br>.description {<br>  text-align: center;<br>}<br><br>.description {<br>  line-height: 1.5;<br>  font-size: 1.5rem;<br>}<br><br>.grid {<br>  display: flex;<br>  flex-wrap: wrap;<br>  width: 80%;<br>  margin-top: 1rem;<br>}<br><br>.card {<br>  margin: 1rem auto;<br>  padding-inline: 3rem;<br>  padding-top: 1rem;<br>  padding-bottom: 3rem;<br>  text-align: left;<br>  color: inherit;<br>  text-decoration: none;<br>  background-color: white;<br>  box-shadow: rgba(0, 0, 0, 0.16) 0px 1px 4px;<br>  transition: color 0.15s ease, border-color 0.15s ease;<br>  width: 25rem;<br>}<br><br>.cardContainer {<br>  display: flex;<br>  align-items: center;<br>  width: 100%;<br>  gap: 10px;<br>}<br><br>.cardHeading,<br>.strickHeading {<br>  display: flex;<br>  align-items: center;<br>  gap: 10px;<br>  width: 100%;<br>}<br><br>.strickHeading {<br>  text-decoration: line-through;<br>}<br><br>.card h2 {<br>  font-size: 1.2rem;<br>  text-align: center;<br>}<br><br>.card p {<br>  margin: 0;<br>  font-size: 1.25rem;<br>  line-height: 1.5;<br>}<br><br>.cardIcon {<br>  font-size: 1.3rem;<br>}<br><br>.cardIcon:hover {<br>  cursor: pointer;<br>  color: red;<br>}<br><br>.strickText {<br>  text-decoration: line-through;<br>}<br><br>.cardActions {<br>  width: 100%;<br>  display: flex;<br>  justify-content: space-between;<br>  margin-top: 7px;<br>}<br><br>.taskBtn {<br>  color: white;<br>  background-color: rgba(119, 8, 133, 0.705);<br>  border: none;<br>  border-radius: 25px;<br>  padding: 10px 15px;<br>  font-size: medium;<br>  margin-top: -35px;<br>}<br><br>.form {<br>  width: 50%;<br>  margin: 1rem auto;<br>  padding: 10px;<br>  box-shadow: 0 1px 3px 0 #d4d4d5, 0 0 0 1px #d4d4d5;<br>}<br><br>.formGroup {<br>  width: 100%;<br>  margin: 1rem 0px;<br>}<br><br>.formGroup label {<br>  display: block;<br>  margin-bottom: 0.5rem;<br>}<br><br>.formGroup input[type=&quot;text&quot;] {<br>  border: 1px solid gray;<br>  outline: none;<br>  border-radius: 5px;<br>  width: 100%;<br>  padding: 10px;<br>}<br><br>.formGroup textarea {<br>  border: 1px solid gray;<br>  border-radius: 5px;<br>  width: 100%;<br>  padding: 10px;<br>  outline: none;<br>}<br><br>.formGroup button {<br>  border: none;<br>  background-color: rgba(119, 8, 133, 0.705);<br>  color: white;<br>  font-weight: bold;<br>  font-size: 15px;<br>  border-radius: 5px;<br>  width: 100%;<br>  padding: 10px;<br>}<br><br>.formGroup button:hover {<br>  background-color: rgb(119, 8, 133);<br>  cursor: pointer;<br>}<br><br>.error {<br>  color: red;<br>  text-align: center;<br>}<br><br>.success {<br>  color: green;<br>  text-align: center;<br>}<br><br>.success a {<br>  color: blue;<br>  text-decoration: underline;<br>}<br><br>@media (max-width: 600px) {<br>  .grid {<br>    width: 100%;<br>    flex-direction: column;<br>  }<br>}</pre><p>Feel free to edit these styles to your preferred appearance.</p><p>In <strong><em>pages/index.tsx</em></strong>, import Firestore from the <strong><em>clientApp.ts</em></strong> file and create a pointer in the todos Collection.</p><p>Then use <strong><em>useState</em></strong> to host the state of our todos, as shown below:</p><pre>import { firestore } from &#39;../firebase/clientApp&#39;;<br><br>import {collection,QueryDocumentSnapshot,DocumentData,query,where,limit,getDocs} from &quot;@firebase/firestore&quot;;<br><br>const todosCollection = collection(firestore,&#39;todos&#39;);<br><br>import { useState } from &#39;react&#39;;<br>const [todos,setTodos] = useState&lt;QueryDocumentSnapshot&lt;DocumentData&gt;[]&gt;([]);<br>const [loading,setLoading] = useState&lt;boolean&gt;(true);</pre><p>A <strong><em>todo</em></strong> object will have a type of <strong><em>QueryDocumentSnapshot&lt;DocumentData&gt;</em></strong>. We will initialize loading to <strong><em>true</em></strong> to avoid accessing <strong><em>todos</em></strong> when they are not fully loaded.</p><p>Next, create a function to get these todos and construct a <strong><em>useEffect</em></strong> hook that will invoke the <strong><em>getTodos</em></strong> method:</p><pre>const getTodos = async () =&gt; {<br>   // construct a query to get up to 10 undone todos <br>   const todosQuery = query(todosCollectio,limit(10));<br>   // get the todos<br>   const querySnapshot = await getDocs(todosQuery);<br>   <br>   // map through todos adding them to an array<br>   const result: QueryDocumentSnapshot&lt;DocumentData&gt;[] = [];<br>   querySnapshot.forEach((snapshot) =&gt; {<br>   result.push(snapshot);<br>   });<br>   // set it to state<br>   setTodos(result);<br>};<br><br>useEffect( () =&gt; {<br>   // get the todos<br>   getTodos();<br>   // reset loading<br>   setTimeout( () =&gt; {<br>     setLoading(false);<br>   },2000)<br>});</pre><p>From above, we are getting <strong>todos</strong> objects and resetting them after every two seconds.</p><p>We need to show these <strong>todos</strong> in a browser. Let’s create a Next.js view to show the fetched todos.</p><p>Add the following code just below the <strong><em>index.tsx </em></strong><strong><em>title</em></strong>, i.e., <strong>&lt;h1className={styles.title}&gt; Todos app&lt;/h1&gt;</strong>.</p><pre>      &lt;div className={styles.grid}&gt;<br>          {loading ? (<br>            &lt;div className={styles.card}&gt;<br>              &lt;h2&gt;Loading...&lt;/h2&gt;<br>            &lt;/div&gt;<br>          ) : todos.length === 0 ? (<br>            &lt;div className={styles.card}&gt;<br>              &lt;h2&gt;No todos&lt;/h2&gt;<br>            &lt;/div&gt;<br>          ) : (<br>            &lt;div className={styles.card}&gt;<br>              {todos.map((todo) =&gt; {<br>                return (<br>                  &lt;div className={styles.cardContainer} key={todo.id}&gt;<br>                    {todo.data().done == false ? (<br>                      &lt;input<br>                        type=&quot;radio&quot;<br>                      /&gt;<br>                    ) : (<br>                      &lt;input<br>                        type=&quot;radio&quot;<br>                        checked<br>                      /&gt;<br>                    )}<br>                    &lt;div<br>                      className={<br>                        todo.data().done == true<br>                          ? styles.strickHeading<br>                          : styles.cardHeading<br>                      }<br>                    &gt;<br>                      &lt;h2&gt;{todo.data().title}: &lt;/h2&gt;<br>                      &lt;p&gt;{todo.data().description}&lt;/p&gt;<br>                    &lt;/div&gt;<br>                    &lt;MdDelete<br>                      className={styles.cardIcon}<br>                    /&gt;<br>                  &lt;/div&gt;<br>                );<br>              })}<br>            &lt;/div&gt;<br>          )}<br>        &lt;/div&gt;<br>        &lt;Link href=&quot;/add-todo&quot; className={styles.taskBtn}&gt;<br>          + New task<br>        &lt;/Link&gt;</pre><p>Above we are displaying a <strong><em>loading..</em></strong> text that checks whether we have todos or not. If we don’t have any, we will display a message; otherwise, existing todos will be mapped and displayed.</p><p>In this case, since we do not yet have todos in Firestore database, you should now be able to see the message in case we don’t have todos from the homepage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*L8pPmELuOraWm-xyz6hBHw.png" /><figcaption>Todo home page</figcaption></figure><h3><strong>Adding a document to Firestore</strong></h3><p>To add a document to Firestore, we need to create a form to input a new todo <strong><em>title</em></strong>, and <strong><em>description</em></strong>.</p><p>In the <strong><em>pages</em></strong> folder, create a file <strong><em>add-todo.tsx</em></strong> setup and add the following code:</p><pre>import { doc } from &quot;@firebase/firestore&quot;;<br>import { setDoc } from &quot;firebase/firestore&quot;;<br>import type { NextPage } from &quot;next&quot;;<br>import { useState } from &quot;react&quot;;<br>import { firestore } from &quot;../firebase/clientApp&quot;;<br>import styles from &quot;../styles/Home.module.css&quot;;<br>import Link from &quot;next/link&quot;;<br><br>const AddTodo: NextPage = () =&gt; {<br>  const [title, setTitle] = useState&lt;string&gt;(&quot;&quot;); // title<br>  const [description, setDescription] = useState&lt;string&gt;(&quot;&quot;); // description<br>  const [error, setError] = useState&lt;string&gt;(&quot;&quot;); // error<br>  const [message, setMessage] = useState&lt;string&gt;(&quot;&quot;); // message<br><br>  const handleSubmit = (e: { preventDefault: () =&gt; void }) =&gt; {<br>    e.preventDefault(); // avoid default behaviour<br><br>    if (!title || !description) {<br>      // check for any null value<br>      return setError(&quot;All fields are required&quot;);<br>    }<br>  };<br><br>  return (<br>    &lt;div className={styles.container}&gt;<br>      &lt;div className={styles.main}&gt;<br>        &lt;h1 className={styles.title}&gt;Add Todo&lt;/h1&gt;<br><br>        &lt;form onSubmit={handleSubmit} className={styles.form}&gt;<br>          {error ? (<br>            &lt;div className={styles.formGroup}&gt;<br>              &lt;p className={styles.error}&gt;{error}&lt;/p&gt;<br>            &lt;/div&gt;<br>          ) : null}<br><br>          {message ? (<br>            &lt;div className={styles.formGroup}&gt;<br>              &lt;p className={styles.success}&gt;<br>                {message}. Proceed to &lt;Link href=&quot;/&quot;&gt;Home&lt;/Link&gt;<br>              &lt;/p&gt;<br>            &lt;/div&gt;<br>          ) : null}<br><br>          &lt;div className={styles.formGroup}&gt;<br>            &lt;label&gt;Title&lt;/label&gt;<br>            &lt;input<br>              type=&quot;text&quot;<br>              placeholder=&quot;Todo title&quot;<br>              onChange={(e) =&gt; setTitle(e.target.value)}<br>              value={title}<br>            /&gt;<br>          &lt;/div&gt;<br><br>          &lt;div className={styles.formGroup}&gt;<br>            &lt;label&gt;Description&lt;/label&gt;<br>            &lt;textarea<br>              placeholder=&quot;Todo description&quot;<br>              onChange={(e) =&gt; setDescription(e.target.value)}<br>              value={description}<br>            /&gt;<br>          &lt;/div&gt;<br><br>          &lt;div className={styles.formGroup}&gt;<br>            &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/form&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default AddTodo;</pre><p>We are setting a basic form with <strong><em>title</em></strong> and <strong><em>description</em></strong> fields. We also have a <strong><em>handleSubmit</em></strong> function that gets called when the form is submitted.</p><p>For now, it just checks for <strong><em>null</em></strong> values. Let’s now handle data to our <strong><em>Collection</em></strong>.</p><p>Start by importing the necessities:</p><pre>import { doc } from &#39;@firebase/firestore&#39;; // for creating a pointer to our Document<br>import { setDoc } from &#39;firebase/firestore&#39;; // for adding the Document to Collection<br>import { firestore } from &#39;../firebase/clientApp&#39;; // firestore instance</pre><p>Create a <strong><em>addTodo()</em></strong> function to add a new <strong><em>Document</em></strong> to the <strong><em>todos</em></strong> Collection:</p><pre>const addTodo = async () =&gt; {<br>    // get the current timestamp<br>    const timestamp: string = Date.now().toString();<br>    // create a pointer to our document<br>    const _todo = doc(firestore, `todos/${timestamp}`);<br>    // structure the todo data<br>    const todoData = {<br>      id: Date.now(),<br>      title,<br>      description,<br>      done: false,<br>    };<br><br>    try {<br>      //add the document<br>      await setDoc(_todo, todoData);<br>      //show a success message<br>      setMessage(&quot;Todo added successfully&quot;);<br>      setError(&quot;&quot;);<br>      //reset fields<br>      setTitle(&quot;&quot;);<br>      setDescription(&quot;&quot;);<br>    } catch (error) {<br>      //show an error message<br>      setError(&quot;An error occurred while adding todo&quot;);<br>    }<br>  };</pre><p>In the code sample above, we are obtaining a timestamp as the <strong><em>Document</em></strong> <strong><em>id</em></strong>. We are saving the data to the Collection.</p><p>If there is an error, we will catch it. Otherwise, we are setting the message. From your browser, open <a href="http://localhost:3000/add-todo."><strong><em>http://localhost:3000/add-todo</em></strong></a>or click on the <strong><em>new task button</em></strong> found on the home page to access the add-todo page</p><p>Your page should be similar to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*2ypmp7sa_jdACWK-WrQY8A.png" /><figcaption>add-todo page</figcaption></figure><p>Fill in the form fields and <strong><em>submit</em></strong>. When the form is successfully submitted, you will get a success message with a link to the home page, as shown below:</p><p>If you get an error, revisit the steps above and see what you may have missed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*p1GbZy7Bit5V88nyNkBg9A.png" /><figcaption>add-todo alert</figcaption></figure><p>In the next step, we will work on updating a <strong><em>document</em></strong>.</p><h3><strong>Updating a document in Firestore</strong></h3><p>In our scenario, updating a document will involve setting a <strong><em>todo</em></strong> object.</p><p>To do this, navigate to <strong><em>pages/index.tsx</em></strong> and import <strong><em>updateDoc</em></strong>.</p><p>Next, create a <strong><em>updateTodo1() and updateTodo2()</em></strong>function, as shown below:</p><pre>const updateTodo1 = async (documentId: string) =&gt; {<br>    // create a pointer to the document id<br>    const _todo = doc(firestore, `todos/${documentId}`);<br><br>    // update the doc by setting done to true<br>    await updateDoc(_todo, {<br>      done: true,<br>    });<br><br>    // retrieve todos<br>    getTodos();<br>  };<br><br>  const updateTodo2 = async (documentId: string) =&gt; {<br>    // create a pointer to the document id<br>    const _todo = doc(firestore, `todos/${documentId}`);<br><br>    // update the doc by setting done to true<br>    await updateDoc(_todo, {<br>      done: false,<br>    });<br><br>    // retrieve todos<br>    getTodos();<br>  };</pre><p>While mapping a todo, add an <strong><em>onClick</em></strong> function to the <strong><em>Radio button as done and undone</em></strong>and call the function as follows:</p><pre>                {todo.data().done == false ? (<br>                      &lt;input<br>                        type=&quot;radio&quot;<br>                        onClick={() =&gt; updateTodo1(todo.id)}<br>                      /&gt;<br>                    ) : (<br>                      &lt;input<br>                        type=&quot;radio&quot;<br>                        checked<br>                        onClick={() =&gt; updateTodo2(todo.id)}<br>                      /&gt;<br>                    )}</pre><p>For any fetched todo, click the <strong><em>Radio</em></strong>button. That <strong><em>todo</em></strong> object will be strikethrough because it updated the done attribute to<strong>true</strong>.</p><p>In the next step, we will work on deleting a todo.</p><h3><strong>Deleting a document in Firestore</strong></h3><p>To delete a document, navigate to <strong><em>pages/index.tsx</em></strong>, import the <strong><em>deleteDoc</em></strong> function, and create a method that will handle the delete (<strong><em>deleteDoc</em></strong>) functionality, as shown below:</p><pre>import {deleteDoc} from &quot;@firebase/firestore&quot;;<br><br>const deleteTodo = async (documentId:string) =&gt; {<br>   // create a pointer to the Document id<br>   const _todo = doc(firestore,`todos/${documentId}`);<br>   // delete the doc<br>   await deleteDoc(_todo);<br>   // retrieve todos<br>   getTodos();<br>}</pre><p>Add a <strong><em>delete</em></strong> icon that is linked to the above function using the <strong><em>onClick</em></strong> event:</p><pre>import { MdDelete } from &quot;@react-icons/all-files/md/MdDelete&quot;;<br> <br>&lt;MdDelete<br>     className={styles.cardIcon}<br>     onClick={() =&gt; deleteTodo(todo.id)}<br>  /&gt;</pre><p>run the <strong><em>npm i react-icons </em></strong>command to install react icons in your project. When you click the <strong><em>delete</em></strong> icon on any fetched t<strong><em>odo</em></strong> item, that object will be deleted from the <strong><em>Collection</em></strong>.</p><h3><strong>Conclusion</strong></h3><p>In this tutorial, we have learned how to handle CRUD operations in a Next.js application.</p><p>This functionality is implemented using a Firebase database which allows us to handle basic backend requests.</p><p>You can access all of this project’s code in this GitHub repository</p><p><a href="https://github.com/NoubissiViany/Todo-App">GitHub - NoubissiViany/Todo-App</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c706214fe694" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 React Best Practices to Improve the Performance of Your Application]]></title>
            <link>https://medium.com/@g696607013/7-react-best-practices-to-improve-the-performance-of-your-application-90eeb762fa68?source=rss-3a812241d63e------2</link>
            <guid isPermaLink="false">https://medium.com/p/90eeb762fa68</guid>
            <dc:creator><![CDATA[Viany Noubissi]]></dc:creator>
            <pubDate>Mon, 21 Aug 2023 16:28:11 GMT</pubDate>
            <atom:updated>2023-08-21T16:28:11.984Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kSz9us65UOjDBEWafPdAw.jpeg" /><figcaption>React Best Practices</figcaption></figure><p>React is one of the most popular front-end frameworks for JavaScript. React best practices are <strong>sets of methods and techniques that produce optimal results, increase efficiency and develop structured processes</strong>.</p><p>Some of React’s best practices you should follow to improve the performance of your application are listed below.</p><h3>1. Avoid Using State (if Possible)</h3><p>React state keeps track of the data which when changed triggers the React component to re-render. When building React applications, avoid using state as much as possible since the more state you use, the more data you have to keep track of across your app.</p><p>One way of minimizing the use of state is by declaring it only when necessary. For instance, if you are fetching user data from an API, store the whole user object in the state instead of storing the individual properties.</p><p>Instead of doing this:</p><pre>const [username, setusername] = useState(&#39;&#39;)<br>const [password, setpassword] = useState(&#39;&#39;)</pre><p>Do this:</p><pre>const [user, setuser] = useState({})</pre><h3>2. Follow Naming Conventions</h3><p>You should always use PascalCase when naming components to differentiate them from other non-component JSX files. For example TextField, NavMenu, and SuccessButton.</p><p>Use camelCase for functions declared inside React components like handleInput() or showElement().</p><h3>3. Dynamically Render Arrays Using Map</h3><p>Use map() to dynamically render repeated HTML blocks. For example, you can use map() to render a list of items in &lt;li&gt; tags.</p><pre>const Items = () =&gt; {<br>  const arr = [&quot;item1&quot;, &quot;item2&quot;, &quot;item3&quot;, &quot;item4&quot;, &quot;item5&quot;];</pre><pre>  return (<br>    &lt;&gt;<br>      {arr.map((elem, index) =&gt; {<br>        &lt;li key={elem+index}&gt;{elem}&lt;/li&gt;;<br>      })}<br>    &lt;/&gt;<br>  );<br>};</pre><p>For comparison purposes, here is how you can render the list without map(). This approach is very repetitive.</p><pre>const List = () =&gt; {<br>  return (<br>    &lt;ul&gt;<br>      &lt;li&gt;Item1&lt;/li&gt;<br>      &lt;li&gt;Item2&lt;/li&gt;<br>      &lt;li&gt;Item3&lt;/li&gt;<br>      &lt;li&gt;Item4&lt;/li&gt;<br>      &lt;li&gt;Item5&lt;/li&gt;<br>    &lt;/ul&gt;<br>  );<br>};</pre><h3>4. Files Related to the Same Component Should Be Arranged in One Folder</h3><p>When deciding on a folder structure for your React app, go for a component-centric one. This means storing all the files concerning one component in one folder.</p><p>If you were creating a Navbar component, for example, create a folder named Navbar containing the component file, the style sheet, and other JavaSript and asset files used in the component.</p><p>A single folder containing all of a component’s files makes it easy to reuse, share, and debug. If you need to see how a component works you only need to open a single folder.</p><p>Keep reusable components in a separate folder. If you have components that more than one part of your application use, consider keeping them in a folder named components. This will help you locate them easily.</p><h3>5. Opt for Fragments Instead of Divs Where Possible</h3><p>React components need to return code wrapped in a single tag usually a &lt;div&gt; or a React fragment. You should opt for fragments where possible.</p><p>Using &lt;div&gt;<strong> </strong>increases the DOM size, especially in huge projects since the more tags or DOM nodes you have, the more memory your website needs and the more power a browser uses to load your website. This leads to lower page speed and potentially poor user experience.</p><p>One example of eliminating unnecessary &lt;div&gt; tags is not using them when returning a single element.</p><pre>const Button = () =&gt; {<br>  return &lt;button&gt;Display&lt;/button&gt;;<br>};</pre><h3>6. Avoid Using Indexes as Key Props</h3><p>React uses keys to uniquely identify items in an array. With keys, React can pinpoint which item has been changed, added, or removed from the array.</p><p>When rendering arrays, you might use the index as the key.</p><pre>const Items = () =&gt; {<br>  const arr = [&quot;item1&quot;, &quot;item2&quot;, &quot;item3&quot;, &quot;item4&quot;, &quot;item5&quot;];</pre><pre>  return (<br>    &lt;&gt;<br>      {arr.map((elem, index) =&gt; {<br>        &lt;li key={index}&gt;{elem}&lt;/li&gt;;<br>      })}<br>    &lt;/&gt;<br>  );<br>};</pre><p>While this sometimes works, using the index as a key can introduce issues especially if the list is expected to change. Consider this list.</p><pre>const arr = [&quot;item1&quot;, &quot;item2&quot;, &quot;item3&quot;, &quot;item4&quot;, &quot;item5&quot;];</pre><p>Currently, the first list item, “Item1” is at index zero, but if you added another item at the beginning of the list, the <strong>“Item1”</strong> index would change to 1 which changes the behaviour of your array.</p><p>The solution is to use a unique value as the index to ensure that the identity of the list item is maintained.</p><h3>7. Eliminate repetitive code</h3><p>If you notice you are writing duplicated code, convert it into components that can be reused.</p><p>For example, it makes more sense to create a component for your navigation menu instead of repeatedly writing the code in every component that requires a menu.</p><p>That’s the advantage of a component-based architecture. You can break down your project into small components you can reuse across your application.</p><p>In conclusion, React is very flexible in how you can use it but following the above practices will help you get the most out of your experience and improve the performance of your application. You can take a look at the repository below to see some of the implementations of the above practices:</p><p><a href="https://github.com/NoubissiViany/react-figma-project">GitHub - NoubissiViany/react-figma-project</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90eeb762fa68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a CRUD RESTFUL API with Node.js and Sequelize]]></title>
            <link>https://medium.com/@g696607013/how-to-build-a-crud-restful-api-with-node-js-and-sequelize-1c43ed5c2645?source=rss-3a812241d63e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c43ed5c2645</guid>
            <dc:creator><![CDATA[Viany Noubissi]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 15:04:52 GMT</pubDate>
            <atom:updated>2023-06-30T15:04:52.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0slisECivg8BL4i7yGKkWg.jpeg" /><figcaption>CRUD RESTFUL API with Node.js and Sequelize</figcaption></figure><p>In this article, you’ll learn how to build a complete CRUD API with Node.js and <strong>Sequelize</strong>. The REST API will run on an <strong>Express.js</strong> server and have endpoints for performing CRUD operations against a MySQL database.</p><p><strong>REST</strong>, an acronym for ‘Representational State Transfer’, determines how the API appears, while <strong>CRUD</strong> is an abbreviation for ‘Create, Read, Update, and Delete’.</p><p><strong>what is sequelize?</strong> it is the process of connecting a Node.js application to an ORM for better database synchronization.</p><p><strong>An ORM</strong> is simply an Object Relational Mapper that helps in data manipulation and querying by the use of objects from the database. Using an ORM optimizes SQL queries making them easy to reuse and maintain.</p><h3><strong>1. Creating Node.js Application</strong></h3><p>A Node.js app comprises three components:</p><ul><li><strong>Import required modules</strong> — The required directive is necessary for loading Node.js modules.</li><li><strong>Create server</strong> — A server listens to the user’s request.</li><li><strong>Read request and return response</strong> — The server created reads the HTTP request and returns a response.</li></ul><p>Knowing all these components will give you a headstart for understanding the concept of Node JS With MySQL. So, you should give prime importance to this subject.</p><p>To build REST API in a Node.js runtime environment, the user performs the following steps:</p><p><strong>Step 1. Create a folder</strong></p><p>Begin by creating a project folder. In this example, you can use crud-api-sequelize. Once the folder is created, navigate to the folder using the terminal:</p><pre>$ mkdir crud-api-sequelize<br>$ cd crud-api-sequelize</pre><p><strong>Step 2. Initialize the Node.js App.</strong></p><p>Then, create a sample Node.js application using the following command:</p><pre>$ npm init</pre><p>Next, you will be prompted to answer some set-up questions. Use the following output for your configuration. Press <strong><em>ENTER </em></strong>to use the displayed default value and be sure to set the main entry point as <strong><em>server.js</em></strong>. This creates a project structure that is easy to maintain.</p><p>The output will look as follows, which will populate the <strong><em>package.json </em></strong>file:</p><pre>{<br>  &quot;name&quot;: &quot;crud-api-sequelize&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;server.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;<br>}</pre><p><strong>Step 3. Install the modules sequelize, body-parser, mysql2, and express.</strong></p><p>Now you can install Sequelize, body-parser, mysql2 and express with the following command:</p><pre>$ npm i express sequelize mysql2 body-parser cors --save</pre><p>The final package.json file must appear as follows:</p><pre>{<br>  &quot;name&quot;: &quot;rud-api-sequelize&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;server.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br> &quot;dependencies&quot;: {<br>    &quot;body-parser&quot;: &quot;^1.19.0&quot;,<br>    &quot;cors&quot;: &quot;^2.8.5&quot;,<br>    &quot;express&quot;: &quot;^4.17.1&quot;,<br>    &quot;mysql2&quot;: &quot;^2.0.2&quot;,<br>    &quot;sequelize&quot;: &quot;^6.29.0&quot;<br>  }<br>}</pre><h3><strong>2. Setting Up Express JS Web Server</strong></h3><ul><li>Begin by creating a new <strong><em>server.js</em></strong> file in the root folder.</li><li>Copie and paste the script below inside in the <strong><em>server.js</em></strong> file:</li></ul><pre>const express = require(&quot;express&quot;);<br>const bodyParser = require(&quot;body-parser&quot;);<br>const cors = require(&quot;cors&quot;);<br><br>const app = express();<br><br>var corsOptions = {<br>  origin: &quot;http://localhost:3001&quot;<br>};<br><br>app.use(cors(corsOptions));<br><br>// parse requests of content-type - application/json<br>app.use(bodyParser.json());<br><br>// parse requests of content-type - application/x-www-form-urlencoded<br>app.use(bodyParser.urlencoded({ extended: true }));<br><br>// simple route<br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>  res.json({ message:&quot;Welcome to CRUD RESTFUL API.&quot;});<br>});<br><br>// set port, listen for requests<br>const PORT = process.env.PORT || 3000;<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on port ${PORT}.`);<br>});</pre><ul><li>Run the app with the command: node server.js.</li><li>Open a web browser and type <strong><em>http://localhost:8080/</em></strong> in the Address bar and the following text will appear</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*4_pZ6T8chkCI8QothjcdyQ.png" /></figure><h3><strong>3. Configuring MySQL Database &amp; Sequelize</strong></h3><p>This is such a critical step in Node JS With MySQL using Sequelize. Configuration is such an important aspect of development and the same is here as well.</p><p>The Node Sequelize combination works on the basis of this configuration. So, let’s have a look.</p><ul><li>Create a <strong><em>config folder</em></strong> in the app folder</li><li>In the <strong><em>config folder</em></strong>, create a <strong><em>db.config.js </em></strong>file by entering the following script</li></ul><pre>module.exports = {<br><br>HOST: &quot;localhost&quot;,<br><br>USER: &quot;root&quot;,<br><br>PASSWORD: &quot;123456&quot;,<br><br>DB: &quot;testdb&quot;,<br><br>dialect: &quot;mysql&quot;,<br><br>};</pre><h3><strong>4. Initializing Sequelize</strong></h3><p>To initialize sequuelize, you need to perform the following steps:</p><p><strong>Step 1: C</strong>reate a <strong><em>models folder</em></strong> in the app folder</p><p><strong>Step 2: </strong>In the <strong><em>models folder</em></strong>, create an <strong><em>index.js</em></strong> file by entering the following code</p><pre>const dbConfig = require(&quot;../config/db.config.js&quot;);<br><br>const Sequelize = require(&quot;sequelize&quot;);<br>const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {<br>  host: dbConfig.HOST,<br>  dialect: dbConfig.dialect,<br>  operatorsAliases: false,<br>});<br><br>const db = {};<br><br>db.Sequelize = Sequelize;<br>db.sequelize = sequelize;<br><br>db.tutorials = require(&quot;./tutorial.model.js&quot;)(sequelize, Sequelize);<br><br>module.exports = db;</pre><p><strong>Note: </strong>You<strong> </strong>must not forget to summon the sync () method in the <strong><em>server.js file</em></strong> as shown below.</p><pre>const db = require(&quot;./app/models&quot;);<br>db.sequelize.sync();</pre><p>If existing tables need to be dropped and the database resynced, enter force: true as the following code</p><pre>db.sequelize.sync({ force: true }).then(() =&gt; {<br><br>console.log(&quot;Drop and re-sync db.&quot;);<br><br>});</pre><h3><strong>5. Defining The Sequelize Model</strong></h3><p>In the <strong><em>models folder</em></strong>, create an a<strong><em>rticle.model.js</em></strong> file and enter the following script in the <strong><em>article.model.js</em></strong></p><pre>module.exports = (sequelize, Sequelize) =&gt; {<br><br>const Article = sequelize.define(&quot;article&quot;, {<br><br>title: {<br><br>type: Sequelize.STRING<br><br>},<br><br>description: {<br><br>type: Sequelize.STRING<br><br>},<br><br>published: {<br><br>type: Sequelize.BOOLEAN<br><br>}<br><br>});<br><br><br>return Article;<br><br>};</pre><p><strong>Note: </strong>In MySQL databases, this model represents tutorial tables. The columns are automatically generated, a few of which are id, description, createdAt, and published.</p><h3><strong>6. Creating the Controller</strong></h3><p>Follow the steps below to create a controller :</p><p><strong>Step 1</strong>: Create a <strong><em>controllers folder </em></strong>in the app folder</p><p><strong>Step 2</strong>: Create an <strong><em>article.controller.js</em></strong> file in the controller folder and enter the following script</p><pre>const db = require(&quot;../models&quot;); // models path depend on your structure<br>const Article = db.article;<br><br>exports.create = (req, res) =&gt; {<br>  // Validate request<br>  if (!req.body.title) {<br>    res.status(400).send({<br>      message: &quot;Content can not be empty!&quot;<br>    });<br>    return;<br>  }<br><br>  // Create an Article<br>  const article = {<br>    title: req.body.title,<br>    description: req.body.description,<br>    published: req.body.published ? req.body.published : false<br>  };<br><br>  // Save Article in the database<br>  Article.create(article)<br>    .then(data =&gt; {<br>      res.send(data);<br>    })<br>    .catch(err =&gt; {<br>      res.status(500).send({<br>        message:<br>          err.message || &quot;Some error occurred while creating the Tutorial.&quot;<br>      });<br>    });<br>};</pre><h3><strong>7. Retrieving Objects and Signle Object</strong></h3><p>To retrieve objects or an object from the database, you need to perform the following script in the <strong><em>article.controller.js </em></strong>file :</p><pre>//Scripts to find all articles<br>exports.findAll = (req, res) =&gt; {<br>  const title = req.query.title;<br>  var condition = title ? { title: { [Op.like]: `%${title}%` } } : null;<br><br>  Article.findAll({ where: condition })<br>    .then(data =&gt; {<br>      res.send(data);<br>    })<br>    .catch(err =&gt; {<br>      res.status(500).send({<br>        message:<br>          err.message || &quot;Some error occurred while retrieving tutorials.&quot;<br>      });<br>    });<br>};<br><br>// Script to find one article with an id<br>exports.findOne = (req, res) =&gt; {<br>  const id = req.params.id;<br><br>  Article.findByPk(id)<br>    .then(data =&gt; {<br>      res.send(data);<br>    })<br>    .catch(err =&gt; {<br>      res.status(500).send({<br>        message: &quot;Error retrieving Tutorial with id=&quot; + id<br>      });<br>    });<br>};</pre><h3><strong>8. Updating An Object</strong></h3><p>To update an Article identified by its id, you need to perform the following script in the <strong><em>article.controller.js </em></strong>file :</p><pre>exports.update = (req, res) =&gt; {<br>  const id = req.params.id;<br><br>  Article.update(req.body, {<br>    where: { id: id }<br>  })<br>    .then(num =&gt; {<br>      if (num == 1) {<br>        res.send({<br>          message: &quot;Article was updated successfully.&quot;<br>        });<br>      } else {<br>        res.send({<br>          message: `Cannot update Article with id=${id}. Maybe Article was not found or req.body is empty!`<br>        });<br>      }<br>    })<br>    .catch(err =&gt; {<br>      res.status(500).send({<br>        message: &quot;Error updating Article with id=&quot; + id<br>      });<br>    });<br>};</pre><h3><strong>9. Deleting An Object and All Objects</strong></h3><p>To delete an Article identified by its id or delete all Articles from an existing database, you need to perform the following script in the <strong><em>article.controller.js </em></strong>file :</p><pre>// Script to delete one article with an id<br>exports.delete = (req, res) =&gt; {<br>  const id = req.params.id;<br><br>  Article.destroy({<br>    where: { id: id }<br>  })<br>    .then(num =&gt; {<br>      if (num == 1) {<br>        res.send({<br>          message: &quot;Article was deleted successfully!&quot;<br>        });<br>      } else {<br>        res.send({<br>          message: `Cannot delete Article with id=${id}. Maybe the Aricle was not found!`<br>        });<br>      }<br>    })<br>    .catch(err =&gt; {<br>      res.status(500).send({<br>        message: &quot;Could not delete Article with id=&quot; + id<br>      });<br>    });<br>};<br><br>//Scripts to delete all articles<br>exports.deleteAll = (req, res) =&gt; {<br>  Article.destroy({<br>    where: {},<br>    truncate: false<br>  })<br>    .then(nums =&gt; {<br>      res.send({ message: `${nums} Article were deleted successfully!` });<br>    })<br>    .catch(err =&gt; {<br>      res.status(500).send({<br>        message:<br>          err.message || &quot;Some error occurred while removing all article.&quot;<br>      });<br>    });<br>};</pre><h3><strong>10. Finding Object by Condition</strong></h3><p>To find all Articles with the condition published =true, you need to perform the following script in the <strong><em>article.controller.js </em></strong>file :</p><pre>exports.findAllPublished = (req, res) =&gt; {<br><br>Article.findAll({ where: { published: true } })<br><br>.then(data =&gt; {<br><br>res.send(data);<br><br>})<br><br>.catch(err =&gt; {<br><br>res.status(500).send({<br><br>message:<br><br>err.message || &quot;Some error occurred while retrieving articles.&quot;<br><br>});<br><br>});<br><br>};</pre><h3><strong>11. Defining Routes</strong></h3><p>If the client sends a request for an endpoint via an HTTP request such as POST, DELETE, PUT, or GET, the user must determine how the server responds.</p><p>Such a response from the server is possible by setting up the below routes:</p><p>/api/articles: GET, POST, DELETE</p><p>/api/articles/:id: GET, PUT, DELETE</p><p>/api/articles/published: GET</p><p>To define routes, you must perform the following steps :</p><p><strong>Step 1: </strong>Create a <strong><em>routes folder</em></strong> in the app folder</p><p><strong>Step 2</strong>: Create an <strong><em>article.routes.js </em></strong>file in the routes folder and enter the following script in the <strong><em>article.routes.js </em></strong>file :</p><pre>module.exports = app =&gt; {<br>  const articles = require(&quot;../controllers/article.controller.js&quot;);<br><br>  var router = require(&quot;express&quot;).Router();<br><br>  // Create a new Articles<br>  router.post(&quot;/&quot;, articles.create);<br><br>  // Retrieve all Articles<br>  router.get(&quot;/&quot;, articles.findAll);<br><br>  // Retrieve all published Articles<br>  router.get(&quot;/published&quot;, articles.findAllPublished);<br><br>  // Retrieve a single Articles with id<br>  router.get(&quot;/:id&quot;, articles.findOne);<br><br>  // Update a Articles with id<br>  router.put(&quot;/:id&quot;, articles.update);<br><br>  // Delete a Articles with id<br>  router.delete(&quot;/:id&quot;, articles.delete);<br><br>  // Create a new Articles<br>  router.delete(&quot;/&quot;, articles.deleteAll);<br><br>  app.use(&#39;/api/articles&#39;, router);<br>};</pre><p><strong>Note: </strong>A controller from the /controllers/tutorial.controller.js has been used in this procedure. The user must also include routes in the server.js. This has to be done just before the app.listen():</p><p>To include routes, you need to perform the following script in the <strong><em>server.js file</em></strong> :</p><pre>require(&quot;./app/routes/article.routes&quot;)(app);<br></pre><p>You can take a look at my DrinckRecipe RESTFUL API on the repository below</p><p><a href="https://github.com/NoubissiViany/Backend-DrinkRecipe-App">GitHub - NoubissiViany/Backend-DrinkRecipe-App</a></p><p>In conclusion, the document gives the reader a script and concise picture of Node.js REST CRUD APIs, Web Express Servers, MySQL databases, and Sequelize</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c43ed5c2645" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REBASE ACADEMY: MY FIRST EXPERIENCE]]></title>
            <link>https://medium.com/@g696607013/rebase-academy-my-first-experience-511967f27fd8?source=rss-3a812241d63e------2</link>
            <guid isPermaLink="false">https://medium.com/p/511967f27fd8</guid>
            <dc:creator><![CDATA[Viany Noubissi]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 10:46:06 GMT</pubDate>
            <atom:updated>2022-12-14T13:32:34.744Z</atom:updated>
            <content:encoded><![CDATA[<p>My first experience at Rebase is quite funny, stressful and enjoyable. Let me explain why my first experience was funny, stressful and enjoyable.</p><p>Firstly, I am a graduate student in the speciality software engineering at Siantou University Institute. So before entering Rebase, I already had some knowledge in the following programming languages HTML, CSS and PHP. Due to all the knowledge that I already had in HTML and CSS, the HTML and CSS course is at a point in time boring. Those introductory lessons started to become funny and interesting when we started practical sessions (projects).</p><p>The most fun and most interesting part of it was that despite all the knowledge that I had in HTML and CSS, those projects were very challenging at certain stages. I immediately realized that the knowledge I had in HTML and CSS was not sufficient for real-life projects, as a result, I really learned new things during this practical session like media query, git-flow etc.</p><p>Secondly, the practical session in HTML and CSS is very stressful due to the pressure our instructors are mounting on us. The pressure that they are mounting on us got me annoyed last time, but I later realized that to be a good programmer, you need to learn how to work under pressure.</p><p>Lastly, the enjoyable part of Rebase is that all of our courses are practical sessions no need to stress about copying notes again. Also, they have a very good learning culture in that they find a way to make fun of everything, in a professional way. However, I like the atmosphere between us.</p><p>Rebase academy is all about putting students on a tested and proven track to becoming world-class full-stack software engineers. All this in the shortest amount of time possible, while getting them job market ready. If this sounds like what you’re looking for, do like I did and check out the website at <a href="https://www.rebaseacademy.com/">https://www.rebaseacademy.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=511967f27fd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>