<?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 Molly Todd on Medium]]></title>
        <description><![CDATA[Stories by Molly Todd on Medium]]></description>
        <link>https://medium.com/@mollyjt89?source=rss-7fdd7a0e6e2c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5NS4cQ6tZzFN_c4i</url>
            <title>Stories by Molly Todd on Medium</title>
            <link>https://medium.com/@mollyjt89?source=rss-7fdd7a0e6e2c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:42:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mollyjt89/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[Using Chart.js for data visualization]]></title>
            <link>https://medium.com/@mollyjt89/using-chart-js-for-data-visualization-b5eac4c6a480?source=rss-7fdd7a0e6e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5eac4c6a480</guid>
            <dc:creator><![CDATA[Molly Todd]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 04:28:29 GMT</pubDate>
            <atom:updated>2023-11-13T21:18:12.945Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently developed a lead management software tool, LeadPulse, as part of a full-stack application using Flask/Python for the backend and React for the frontend. To make the app visually appealing and insightful, I decided to incorporate data visualization using Chart.js.</p><p>Chart.js stood out as the ideal library for my project. I envisioned a Pie Chart to break down lead types (Instagram, FaceBook, referral, etc.) and a bar graph to illustrate the count of leads at various stages (new lead, negotiating, proposal, won, lost, etc.).</p><p>As a new developer, learning libraries and frameworks presented its challenges. Creating the graph, especially the bar chart, was a bit challenging initially. With my experience, I want to guide you through the process step by step, potentially saving you a lot of time.</p><p>Let’s focus on creating the bar graph:</p><ol><li>Download Chart.js: Ensure you have the Chart.js library. I used version “chart.js”: “⁴.4.0”.</li></ol><p>“chart.js”: “⁴.4.0”</p><p>2. Decide on the data points that will be visually represented. Consider insights that would enhance dashboard visibility. For me, it was essential to understand the distribution of leads across various stages.</p><p>3. Develop a separate component for the Bar graph.</p><p>4. Import the necessary dependencies from React and Chart.js</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*q1FPBqgSXqqFQCUpgW8PYg.png" /></figure><p>5. Use the useState hook to manage the state of lead stages, their respective counts, and the data being fetched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*s2wRkDtP49wskDiPiaFm6g.png" /></figure><p>6. Fetch the data. Use the ‘useEffect’ hook to fetch lead data from an API endpoint. Update the state with lead stages and their counts. Ensure the API response aligns with the values you’re referencing. In my case, it’s the stage (won, lost, negotiating, etc.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*mtDuLElTupG-b5erFAjC-w.png" /></figure><p>7.Define a function to generate colors based on the number of leadstages. I specified ‘violet’ because it match my UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*zx5ErUs-_u-1AO0eHedDxw.png" /></figure><p>8. Use another useEffect hook to render the bar chart using Chart.js when the data is fetched. Destroy the existing chart. This is done to prevent memory leaks and ensure the chart is properly cleaned up before re-rendering. It’s good practice to destroy the existing chart. ‘chartRef.current’ checks that the chart canvas element is available. It’s a guard against trying to operate a non-existent or uninitialized chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*zTdgLJtgKsJxc9q3b18idA.png" /></figure><p>9. In the return statement, conditionally render the canvas element when the data is fetched, or show a loading message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YIA60_D3KmN1Pa5xpqcnsg.png" /></figure><p>And finally, import and render BarChart into your parent component. Mine is in my home component. Here is the finished product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*KebpB2pyJSWHkTlHVd-_7A@2x.jpeg" /></figure><p>Following these steps, you can easily integrate a bar graph into your React application using Chart.js. I hope this makes data visualization a breeze for you! Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5eac4c6a480" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UI Design with Chakra-UI]]></title>
            <link>https://medium.com/@mollyjt89/ui-design-with-chakra-ui-5995df07e074?source=rss-7fdd7a0e6e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5995df07e074</guid>
            <dc:creator><![CDATA[Molly Todd]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 05:49:08 GMT</pubDate>
            <atom:updated>2023-10-23T05:49:08.859Z</atom:updated>
            <content:encoded><![CDATA[<h3>UI Design with Chakra</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvlQ-g6Un6fau1C9jmRPgQ.png" /></figure><p>User Interface design is a fundamental aspect of web development. Not going to lie, it is hard to create visually appealing and user-friendly interfaces from scratch. Chakra-UI, (a React component library) simplifies the process of designing UIs. Let’s explore what Chakra-UI is, why it’s a great choice, and how you can quickly implement it into your web projects. I’ll also show various design components and provide examples to demonstrate its ease and flexibility.</p><h3>What is Chakra-UI?</h3><p>Chakra-UI is a set of customizable UI components designed for React applications. It offers a wide range of pre-designed components such as buttons, forms, modals, tooltips, and more. Chakra-UI makes it easier for developers to create visually appealing and functional web applications without the need to build every component from scratch.</p><h3>Why Choose Chakra-UI?</h3><p>Chakra-UI’s popularity stems from several advantages:</p><ol><li>Simplicity: Chakra-UI is built with simplicity in mind. It offers a clean and intuitive API, allowing developers to create UI components with minimal effort.</li></ol><p>2. Customization: Chakra-UI components are highly customizable. You can easily change colors, styles, and other properties to match your project’s design.</p><p>3. Accessibility: Accessibility is a priority in Chakra-UI. All components are designed with accessibility features, ensuring that your web application is inclusive and usable by a broad audience.</p><p>4. Community Support: Chakra-UI has a vibrant and active community. You can find ample resources, tutorials, and pre-designed themes to jumpstart your UI development.</p><h3>Getting Started with Chakra-UI</h3><p>Let’s dive into implementing Chakra-UI in your React application. Here’s a step-by-step guide to get you started:</p><h3>Step 1: Create a React App</h3><p>Begin by creating a new React project using Create React App or your preferred setup.</p><pre>npx create-react-app my-chakra-ui-app</pre><h3>Step 2: Install Chakra-UI</h3><p>Navigate to your project folder and install Chakra-UI and its dependencies.bashCopy code</p><pre>cd my-chakra-ui-app<br>npm install @chakra-ui/react @emotion/react @emotion/styled framer-motion</pre><h3>Step 3: Setting Up ChakraProvider</h3><p>Open your src/index.js or src/index.js file and import ChakraProvider.</p><pre>import { ChakraProvider } from &quot;@chakra-ui/react&quot;;</pre><p>Wrap your App component with ChakraProvider at the root level</p><pre>ReactDOM.render(<br>  &lt;ChakraProvider&gt;<br>    &lt;App /&gt;<br>  &lt;/ChakraProvider&gt;,<br>  document.getElementById(&quot;root&quot;)<br>);</pre><h3>Step 4: Using Chakra-UI Components</h3><p>You can now use Chakra-UI components in your React components. Let’s showcase a few design components to get you started.</p><h4>Buttons and Forms</h4><p>You can create buttons and forms with Chakra-UI, like this simple login form:</p><pre>import { Input, Button, FormControl, FormLabel } from &quot;@chakra-ui/react&quot;;</pre><pre>function LoginForm() {<br>  return (<br>    &lt;form&gt;<br>      &lt;FormControl&gt;<br>        &lt;FormLabel&gt;Email&lt;/FormLabel&gt;<br>        &lt;Input type=&quot;email&quot; /&gt;<br>      &lt;/FormControl&gt;<br>      &lt;FormControl&gt;<br>        &lt;FormLabel&gt;Password&lt;/FormLabel&gt;<br>        &lt;Input type=&quot;password&quot; /&gt;<br>      &lt;/FormControl&gt;<br>      &lt;Button type=&quot;submit&quot;&gt;Login&lt;/Button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*gHpTr6XwhB7jN4s3_fq8zw.png" /></figure><h4>Alerts and Notifications</h4><p>Chakra-UI offers components for displaying alerts and notifications, such as success messages or error alerts:</p><pre>import { Alert, AlertIcon } from &quot;@chakra-ui/react&quot;;</pre><pre>function SuccessAlert() {<br>  return (<br>    &lt;Alert status=&quot;success&quot;&gt;<br>      &lt;AlertIcon /&gt;<br>      Login successful!<br>    &lt;/Alert&gt;<br>  );<br>}</pre><h4>Modals and Dialogs</h4><p>Implementing modals and dialogs is straightforward with Chakra-UI. Here’s an example of a simple confirmation modal:</p><pre>import { Button, Modal, ModalOverlay, ModalContent, ModalHeader, ModalBody, ModalFooter } from &quot;@chakra-ui/react&quot;;</pre><pre>function DeleteConfirmationModal({ isOpen, onClose, onDelete }) {<br>  return (<br>    &lt;Modal isOpen={isOpen} onClose={onClose}&gt;<br>      &lt;ModalOverlay /&gt;<br>      &lt;ModalContent&gt;<br>        &lt;ModalHeader&gt;Confirm Deletion&lt;/ModalHeader&gt;<br>        &lt;ModalBody&gt;Are you sure you want to delete this item?&lt;/ModalBody&gt;<br>        &lt;ModalFooter&gt;<br>          &lt;Button colorScheme=&quot;red&quot; onClick={onDelete}&gt;<br>            Delete<br>          &lt;/Button&gt;<br>          &lt;Button variant=&quot;ghost&quot; onClick={onClose}&gt;<br>            Cancel<br>          &lt;/Button&gt;<br>        &lt;/ModalFooter&gt;<br>      &lt;/ModalContent&gt;<br>    &lt;/Modal&gt;<br>  );<br>}</pre><h4>Tooltips and Popovers</h4><p>Chakra-UI allows you to add tooltips and popovers for providing extra information or explanations. For instance, you can create a tooltip for a question mark icon that explains a feature:</p><pre>import { Tooltip } from &quot;@chakra-ui/react&quot;;</pre><pre>function InfoTooltip({ content }) {<br>  return &lt;Tooltip label={content}&gt;ℹ️&lt;/Tooltip&gt;;<br>}</pre><p>These examples illustrate how you can easily integrate Chakra-UI components into your projects, improving the design and functionality of your web applications.</p><h3>Customizing Chakra-UI Components</h3><p>Customization is at the core of Chakra-UI. You can modify the appearance of components by passing props. For example, changing the button’s color to blue:</p><pre>&lt;Button colorScheme=&quot;blue&quot; size=&quot;lg&quot;&gt;<br>  Click Me<br>&lt;/Button&gt;</pre><p>Chakra-UI also provides a robust theming system, allowing you to define your own styles and customize the entire UI to match your project’s design.</p><h3>Conclusion</h3><p>Chakra-UI is a fantastic choice for building beautiful and accessible user interfaces in your React applications. In this comprehensive guide, we introduced you to Chakra-UI, explained why it’s a great option, and provided a step-by-step guide to getting started. We also showcased various design components to demonstrate its ease and flexibility. Whether you’re a newbie or an experienced developer, Chakra-UI simplifies the UI development process and empowers you to create visually stunning web applications with ease.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5995df07e074" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Planting the Seeds of Data: An Easy Guide to Seeding a Database in Python with SQLAlchemy]]></title>
            <link>https://medium.com/@mollyjt89/planting-the-seeds-of-data-an-easy-guide-to-seeding-a-database-in-python-with-sqlalchemy-5198a0d3ffa5?source=rss-7fdd7a0e6e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5198a0d3ffa5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <dc:creator><![CDATA[Molly Todd]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 02:57:53 GMT</pubDate>
            <atom:updated>2023-10-04T00:27:06.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*0B6Xas8pQzNHq8IJiTGomQ.png" /></figure><p>So…you need to set up a database to store all that precious data your users will generate? Fear not, my friends, because today we’re going to talk about how to seed a database in Python, using the SQLAlchemy library.</p><p>Imagine your database as a garden. Seeding it is like planting the first few seeds. It’s a crucial step, and we’ll make it as enjoyable as possible. Let’s get our hands dirty!</p><p><strong>Getting Started: </strong>What’s Seeding, Anyway?</p><p>Seeding a database essentially means populating it with some initial data, like creating the first few rows of a spreadsheet. In Python, we use SQLAlchemy to interact with databases. It’s our trusted gardening tool.</p><p>But before we dive into the Python code, let’s talk models. Not the fashion kind — I’m talking about how you structure your data.</p><p><strong>Laying the Foundation:</strong> Creating Models</p><p>Think of models as the blueprints for your data — they define how your data is structured and organized. In SQLAlchemy, you define models as Python classes, which is pretty cool because it’s like designing your dream house. Before we get to into the weeds, let’s make sure you have everything ready and run through a quick checklist:</p><p><strong>Steps to start seeding:</strong></p><ol><li>Make a directory for your new application. cd into that directory.</li><li>Setup your virtual environment (to manage dependencies) by running:</li></ol><p>pipenv shell</p><p>3. Install SQLAlchemy</p><p>pip install sqlalchemy</p><p>4. Create seed file</p><p>touch seed_database.py</p><p>For our imaginary app, let’s say we’re building a library catalog. Back to the bit about models. We’ll need a Book model, right? Here&#39;s what your model file might look like in your models.py file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*k7RFu_WzhMRbOegcSHAYkA.png" /></figure><p>Here, we’ve defined a Book class with attributes like title, author, and year_published. SQLAlchemy is like the architect who turns these class definitions into database tables.</p><p><strong>Time to Get Seedy With It</strong></p><p>Now that we have our models set up, it’s time to plant some data seeds. Let’s say we want to add a few books to our library catalog. Here’s how you can do it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2HU5ONi-_TPqWho4U0Y28g.png" /></figure><p>In this code, we’re creating an SQLAlchemy session, which is like our gardener’s basket. We then create some Book instances and add them to our session. Finally, we commit the changes, run the seed file and voila – our seeds are planted in the database!</p><p><strong>Feeling lazy or …a desire to be efficient? Automate it!</strong></p><p>Seeding a database is all fun and games until you have hundreds or thousands of records to plant. In that case, manual seeding can feel a bit like digging with a spoon.</p><p>Fear not, because we can automate this process with Python. You could create a function to generate random book data, and then call it a bunch of times to populate your database. Here is the function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAcyaMl-TnrmRhZvVnTdDw.png" /></figure><p>Your full seed_database.py file should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VflsxqI8tg3Dj68-3DgTEg.png" /></figure><p><em>Don’t forget to run </em><em>python seed_database.py (replace with your file name) again to update the tables.</em></p><p>Now we’re talking! We’ve got ourselves a function that generates random book data, and we’ve planted 10 books with minimal effort. It’s like having a magical gardening gnome do the work for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*Xq4vX5dIu4h01HpDzkVJgA.png" /></figure><p>But Wait, There’s More: Using Seeded Data</p><p>Now that our database is nicely seeded, let’s see how we can put that data to good use. Suppose you want to fetch all the books published after 2000. SQLAlchemy makes it a breeze with these few lines of code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_KEKb7ZHtESp_rBdlCqSFQ.png" /></figure><p>^ you can put this above the session.commit().</p><p>Run python seed_database.py and you should see the following output in your terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*UQ1C_5-tj3mVf3gxczGQCQ.png" /></figure><p>All books published after 2000!</p><p>And there you have it — you’ve harvested the fruits of your seeding labor! You can fetch, update, and delete data with SQLAlchemy’s expressive queries, just like picking ripe tomatoes from your garden.</p><p>Wrapping It Up</p><p>Seeding a database may sound like a daunting task, but it’s more like playing in the sandbox with your favorite toys. With SQLAlchemy and a bit of Python magic, you can effortlessly populate your database and build the foundation for your web application.</p><p>So, don’t be afraid to get your hands dirty, plant those data seeds, and watch your database garden flourish. Happy coding, and may your data harvest be bountiful! 🌱📚🌻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5198a0d3ffa5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React State: Lifting, Managing, and Why It Matters]]></title>
            <link>https://medium.com/@mollyjt89/react-state-lifting-managing-and-why-it-matters-d6881db61f32?source=rss-7fdd7a0e6e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6881db61f32</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[beginner-programmers]]></category>
            <category><![CDATA[react-state]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Molly Todd]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 05:07:29 GMT</pubDate>
            <atom:updated>2023-09-09T05:07:29.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eSdwxopm3wesun5M" /></figure><p>Working with Vanilla JavaScript can feel tedious. Its imperative nature often leads to excessive steps for even simple tasks, and managing large-scale applications can become challenging. This is why React, among other frameworks, has become the preferred choice, thanks to its declarative-style language and component-based rendering.</p><p>I’m currently a student at Flatiron School, studying software engineering. I’ve recently completed phases 1 and 2, which covered Vanilla JavaScript and React. The most significant learning curve I experienced in JavaScript was, well, everything. I came from a tech sales background with no prior programming experience.</p><p>React had me facing a double learning curve. I mean, there was the whole deal with new syntax, and passing props? I was constantly scratching my head. But speaking of diving into the nitty-gritty, let’s now talk about ‘state’.</p><h3>What Is State and Why Is It Important?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/0*AvqxHOpMy4k4QZ2A" /></figure><p>Think of state in React like a thermostat in your home. It keeps track of the current temperature setting. When you want to make the room warmer or cooler, you adjust the thermostat. React’s state is similar; it’s like a dynamic setting that controls what’s displayed on your web page, and you can change it to update your app’s behavior.</p><p>In React, we use State so that our components can keep their own information. Without it, our components wouldn’t be able to hold or change their data, and our app wouldn’t be able to do cool stuff or react to what we do. Let’s dive into a practical example of when state may come up.</p><p>In the following code snippet, we are using state to fetch to manage and display data:</p><pre>import React, { useState, useEffect } from ‘react’;<br>function FetchData() {<br>const [data, setData] = useState(null);<br>useEffect(() =&gt; {<br>// Replace &#39;https://api.example.com/data&#39; with the actual API endpoint<br>fetch(&#39;https://api.example.com/data&#39;)<br>.then(response =&gt; response.json())<br>.then(fetchedData =&gt; {<br>setData(fetchedData);<br>});<br>}, []);<br>return (<br>&lt;div&gt;&lt;p&gt;{data.message}&lt;/p&gt;&lt;/div&gt;<br>)}<br>export default FetchData;</pre><p>Is state necessary in the code above?</p><p>YES.</p><p>Why?</p><p>In a nutshell, it allows your component to manage and update the fetched data, which is essential for a dynamic and responsive UI. Here is the detailed why.</p><p><strong>Managing Data: </strong>When you fetch data from an external API, you need a place to store and manage that data within your component. State, created with useState, provides that storage container. You wouldn’t have an empty basket after going grocery shopping, right? In my above example, const [data, setData] = useState(null); initializes a state variable (basket) to hold the fetched data(groceries).</p><p><strong>Reactivity: </strong>In React, when something in your component changes (like the data you fetched), React automatically updates what’s shown on the screen. So, by using setData(fetchedData), you’re telling React to remember the new data. When it does, React “notices” the change and refreshes your component’s display with the updated data. This way, your component can always show the latest information on the screen for users to see.</p><p><strong>Conditional Rendering with State: </strong>Think of conditional rendering as having a magic button that lets you display different things on the screen based on whether you have the data you need or not. This magical button is your state in React. When you fetch data, you use this state to decide what to show. For instance, you can display a message like “Loading…” while you’re waiting for the data (because your state knows you’re waiting), and once the data arrives, your state lets you switch to showing the actual data. To manage this switching, you might use an extra state variable to help you keep track of what’s currently displayed on the screen. This way, your component knows when to show what, making your user interface responsive and dynamic.</p><p>Without using state, you wouldn’t have a way to store and update the data within your component. As a result, your component wouldn’t be able to display the fetched data or respond to changes in that data. So, in this example, using state is necessary to manage and display the fetched data effectively. Now let’s talk about lifting state.</p><h3>Lifting and Moving State</h3><p>“Lifting state up” — something I heard over and over during my first days with React, but I had no clue what it meant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/0*5Pxeif_LlFLEVAAW" /></figure><p>”Lifting state up” is when you move the management of a piece of data or state from a child component to a parent component. It’s called “lifting state up” because you’re essentially lifting the responsibility of managing that data to a higher-level component, making it accessible to both the parent and its child components. So why move it? It’s easier for the parent to manage it. Plus, then all the children components will have access to it.</p><p>Let’s say you have a to-do list app. You want to manage the list of to-dos in the parent component and display them in child components. Here’s how you can move the state:</p><ol><li>Identify the State to Be Moved: Determine which part of the state you want to manage in a child component. In this case, let’s say you want a child component to be responsible for adding new to-do items:</li></ol><pre>function TodoApp() {<br>// Parent component manages the list of to-dos<br>const [todos, setTodos] = useState([<br>{ id: 1, text: &#39;Buy groceries&#39; },<br>{ id: 2, text: &#39;Clean the house&#39; },<br>{ id: 3, text: &#39;Take out the trash&#39; },<br>]);</pre><p>2. In the parent component (TodoApp), create a function that child components can call to update the state. For example, you might create a function called addTodo to add new to-do items:</p><pre>// Parent Component (TodoApp)<br>function TodoApp() {<br>// Parent component manages the list of to-dos<br>const [todos, setTodos] = useState([<br>{ id: 1, text: &#39;Buy groceries&#39; },<br>{ id: 2, text: &#39;Clean the house&#39; },<br>{ id: 3, text: &#39;Take out the trash&#39; },<br>]);<br>// Function to add a new to-do<br>const addTodo = (newTodo) =&gt; {<br>setTodos([…todos, newTodo]);<br>};// … Rest of the component}</pre><p>3. Pass the function you created in step 2 (addTodo) as a prop to the child component. This allows the child component to call the function and update the state when needed:</p><pre>// Parent Component<br>function TodoApp() {<br>// Parent component manages the list of to-dos<br>const [todos, setTodos] = useState([<br>{ id: 1, text: ‘Buy groceries’ },<br>// Function to add a new to-do<br>const addTodo = (newTodo) =&gt; {<br>setTodos([…todos, newTodo]); };<br>return (<br>&lt;div&gt;<br>{/* Pass the todos state and the addTodo function as props */}<br>&lt;TodoList todos={todos} addTodo={addTodo} /&gt;<br>&lt;/div&gt;<br>);<br>}</pre><p>Now that we’ve seen how to manage state within components and even pass that state to child components, it’s time to explore a more modern and streamlined approach to state management in React.</p><h3>useState Hook (Functional Components)</h3><p>React used to rely heavily on class components, but now we have functional components. They are simple and preferred. One of the ways to manage state in functional components is by using the useState hook at the top of the component.</p><h4>To make things as simple as possible here, look at the difference between using a class component for a simple counter:</h4><pre>import React, { Component } from ‘react’;<br>class CounterClass extends Component {<br>constructor() {<br>super();<br>this.state = {<br>count: 0,<br>};<br>}<br>incrementCount = () =&gt; {<br>this.setState({ count: this.state.count + 1 });<br>};<br>render() {<br>return (<br>&lt;div&gt;<br>&lt;p&gt;Count: {this.state.count}&lt;/p&gt;<br>&lt;button onClick={this.incrementCount}&gt;Increment&lt;/button&gt;<br>&lt;/div&gt;<br>)}};<br>export default CounterClass;</pre><h4>And a functional component in a simple counter:</h4><pre>import React, { useState } from ‘react’;<br>function CounterFunction() {<br>const [count, setCount] = useState(0);<br>const incrementCount = () =&gt; {<br>setCount(count + 1);<br>};<br>return (<br>&lt;div&gt;<br>&lt;p&gt;Count: {count}&lt;/p&gt;<br>&lt;button onClick={incrementCount}&gt;Increment&lt;/button&gt;<br>&lt;/div&gt;<br>);<br>}<br>export default CounterFunction;</pre><p>The takeaway: functional components are concise and easy to read.</p><h3>As Your React App Grows, Managing State Becomes Crucial. Here Are Some Tips:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/0*-WDL6MxrC-Xn8x-T" /></figure><ul><li>Keep your state as minimal as possible.</li><li>Follow a clear naming convention for your state variables.</li><li>Use functional updates when modifying state based on the previous state.</li><li>Class components aren’t obsolete but functional components with hooks have become the norm. Use class components for specific scenarios or when working with legacy code. Otherwise, go with functional components.</li><li>Good component organization is key. Keep your code clean and maintainable by separating concerns. Each component should have a clear and single responsibility.</li></ul><p>Thank you for reading my blog post. I hope this was informative and helped you gain a better understanding of state compared to when you first arrived!</p><p>Happy coding,</p><p>Molly T.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6881db61f32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common JavaScript Error Messages: A Beginners Guide to Debugging]]></title>
            <link>https://medium.com/@mollyjt89/common-javascript-error-messages-a-beginners-guide-to-debugging-bda275c2cbce?source=rss-7fdd7a0e6e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bda275c2cbce</guid>
            <category><![CDATA[javascript-error]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-error-handling]]></category>
            <dc:creator><![CDATA[Molly Todd]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 20:32:53 GMT</pubDate>
            <atom:updated>2023-08-18T23:03:42.978Z</atom:updated>
            <content:encoded><![CDATA[<p>Picture this: It’s Monday afternoon. You‘ve got your <a href="https://open.spotify.com/playlist/37i9dQZF1DWZZbwlv3Vmtr?si=249be0d1d25248ae">Focus Flow playlist</a> on. You’ve written lines and lines of code. Your deadline isn’t until Friday. This is the best Monday ever. Before logging off for the day, you open your console. Your heart drops. You see more error messages than you can count. You are now moments away from an existential crisis.</p><p>This is a common feeling that beginner developers have <a href="https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu?si=1fd0625428334840">(“It’s me, hi, I’m the problem it’s me. )</a>. That said, error messages are in fact our friend.</p><p>Error messages serve as little clues that lead you straight to the source problem of your code. Understanding error messages is key to reduce time spent on trial-and-error debugging. It improves efficiency of addressing the problem.</p><p>Now that we’ve befriended error messages, let’s talk about four common types of JavaScript error messages.</p><h3><strong>SyntaxErrors : Identifying Code Structure Issues</strong></h3><p>These error messages are thrown when you break the rules of JavaScript language syntax. <a href="https://www.sciencedirect.com/topics/engineering/syntax-error">Let’s take a look at the common causes of syntax errors:</a></p><ol><li>Missing/unmatched parenthesis &amp; curly braces</li><li>Omitting semicolons (not always required, but an error can happen.)</li><li>Misspelled keywords/variables</li><li>Using reserved words (assigning the value of ‘if’)</li></ol><p>You can interpret a Syntax Error by breaking down the message:</p><pre>Uncaught SyntaxError: Unexpected token ‘;’<br> at myScript.js:3:15</pre><p>Here’s what we know:</p><ul><li><strong><em>Uncaught SyntaxError</em></strong> is the type of error</li><li><strong><em>Unexpected token: </em></strong>shows the unexpected token. In this case it is a semi colon, but could also be a ‘)’ or ‘}’</li><li><strong><em>At myScript.js:3:15:</em></strong><em> </em>pinpoints where the error is. It’s on line 3, column 15 of the file ‘myscript.js’</li></ul><p>Consider leveraging tools like the <a href="https://eslint.org/docs/latest/use/configure/">ESLint extension</a> to help prevent errors. Keep in mind ESLint is static — it analyzes code without running it.</p><p>Embrace SyntaxErrors. They will make you a more skilled coder in the long run.</p><h3>Reference Errors: Unresolved Variables &amp; Scope</h3><p>Reference Errors occur when accessing a variable/property that does not exist. You might think, ‘does not exist? how? It’s right there!’<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError"> It’s a moment of frustration that can be both confusing and enlightening.</a></p><p>Here is an example you may encounter:</p><pre>Uncaught ReferenceError: myVariable is not defined at myScript.js:3:9</pre><p>Let’s unpack this a bit more.</p><ul><li><strong><em>Uncaught ReferenceError: </em></strong>This error type indicates that you’re using something that JavaScript doesn’t recognize in the current context</li><li><strong><em>myVariable is not defined:</em> </strong>The error message singles out the issue — in this case, the elusive ‘myVariable’</li><li><strong><em>myScript.js:3:9</em>:</strong> These coordinates pinpoint the exact location of the error: line 3, column 9 of the ‘myscript.js’ file</li></ul><p>Easy enough, right?</p><p>Sort of. You now know what is causing issues in your code. But how do you fix it?</p><p><strong>Scope Chain Examination: F</strong>ollow the clues. Trace the variable’s path to its current location. Is it truly accessible within this scope, or does it belong to a higher scope?</p><p><strong>Looking Inside the Function:</strong> is the variable declared within that function or a higher scope? Variables declared within functions are <em>not </em>accessible outside of those functions, unless the variable is declared without ‘const’, ‘let’ or ‘var’. then it is implicitly global.</p><p><strong>Block examination: </strong>Similar rules apply to blocks like ‘if’, ‘while’, or ‘for’. Variables living in blocks remain locked within them.</p><p><strong>Be unique.</strong> Your naming conventions, that is. Do your function’s parameters or it’s local variables have the same name as variables in outer scopes? Keeping names distinct reduces the risk of unexpected Reference Errors.</p><p><strong>Allies in Error: </strong>Remember how error messages are your friends? Well, so is Console Logging. Add console.log() statements before and after the line in question. You can see the state of the variables leading up to the error.</p><p><strong>The Livesaver:</strong> Linting Tools (shout out again to ESLint extension) can help catch scope-related issues.</p><p>With practice, you’ll master untangling referenceError mysteries.</p><h3><strong>TypeErrors: Confusing JavaScript With Unfit Data</strong></h3><p>TypeErrors are triggered when you’re supposed to use a certain kind of information for a task, but you end up using a different kind of information that doesn’t work correctly for that task. Square peg, round hole. Trying to multiply a number by a string? Well, just like your last bad date, they are not each other’s type. Except JavaScript will let you down easy with a Type error. This also goes for arrays. Different types of arrays are not compatible. They cannot be combined.</p><p>Consider this scenario:</p><pre>let numArr = [1,2,3,4];<br>let text = &quot;5&quot;<br>let totalNum = numArr.concat(text);</pre><p>The outcome? ‘TypeError: numbers.concat is not a function’. Arrays of different types simply refuse to merge.</p><p>Unassigned variables also lead to type errors. In this example, a variable is declared but not assigned:</p><pre>let name;<br>let lastName= &quot;Johnson&quot;<br>let fullName = name + lastName<br>TypeError: Cannot read property &#39;valueOf&#39; of undefined.</pre><p>When you take the time to understand and break down the above error you realize— the fullName variable only has a string assigned to part of the expression. The variable name remains undefined and mysterious. The error is warranted — we can’t sum(+) up the unknown.</p><p>Another reason for this type of error might be function related. Are you calling a function from a non-function? It’s like trying to make a phone call to someone who doesn’t have a phone. In JavaScript terms, this translates to calling a function on incompatible data:</p><pre>let phoneGreeting = &quot;Hello!&quot;;<br>phoneGreeting();</pre><pre>“Please leave your message after the tone. TypeError: phoneGreeting is not a function.”</pre><p>Remember, Type Errors are your guideposts to the world of data type compatibility. By embracing these errors as opportunities to understand and respect JavaScript’s data type rules, you’ll unlock a deeper understanding of how to work with different types of information.</p><h3><strong>RangeErrors: Out-Of-Bounds</strong></h3><p>RangeErrors are JavaScripts way of letting you know that your code is working with values beyond what it can handle. <a href="https://matcha.fyi/rangeerror-maximum-call-stack-size-exceeded/">There are a few examples that might be helpful to cover here</a>:</p><p>If you have an array of numbers :</p><pre>const numbers = [1,2,3,5]<br>console.log(numbers[7])</pre><p>In this snippet, you are trying to access a number at the 7th index of the ‘numbers’ array. However, the array only has indices from 0 to 3 (since arrays are zero-indexed), resulting in an error message like:</p><pre>RangeError: Invalid array index at :2:17</pre><p>It is worth noting that negative indexes also trigger RangeErrors. Remember, indexes start at 0, so a negative index is invalid. This seemed like a no brainer to me, until realizing that <a href="https://saturncloud.io/blog/understanding-python-numpy-array-negative-indexing-a-comprehensive-guide/#:~:text=Negative%20indexing%20is%20a%20feature,versatile%20tool%20for%20data%20manipulation.">Python allows negative indexing to access elements from an end of an array. </a>JavaScript does not support this feature.</p><p>RangeErrors are also commonly thrown in scenarios involving the call stack, <a href="https://www.geeksforgeeks.org/what-is-the-call-stack-in-javascript/">which keeps track of function calls during program execution</a>. A common occurance is the “Maximum call stack size exceeded” error, often caused by a function calling itself recursively without proper termination. This can overwhelm JavaScript, triggering a RangeError accompanies with the ‘maximum call stack’ message. Identifying this issue prompts further research of <a href="https://www.educative.io/answers/introduction-to-recursion-in-javascript">termination conditions</a> as a potential solution.</p><p>The most important takeaway is that RangeErrors are guardrails that alert you when your code ventures beyond the boundaries.</p><p>So, the next time you’re faced with a barrage of error messages in your console, remember that each message is a clue leading you closer to the treasure. Reference the steps to take when understanding the error message and how to diagnose the issue. These are the checkpoints on your path to becoming a proficient JavaScript bug zapper! With every bug you crush, you inch closer to mastery, transforming even the most frustrating Mondays into rewarding victories. Happy coding!</p><p>Sincerely,</p><p>Molly Todd</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bda275c2cbce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>