Logo

dev-resources.site

for different kinds of informations.

# Storing Data in the Database with JavaScript

Published at
8/10/2024
Categories
webdev
reactjsdevelopment
localstorage
softwaredevelopment
Author
michaelmoranis
Author
14 person written this
michaelmoranis
open
# Storing Data in the Database with JavaScript

During the development of my task list application, one of the coolest features I managed to implement was the ability to store data in the database. Using JavaScript, I created a function that sends user data to a server. This not only ensures that the data is securely saved but also provides a smooth and pleasant user experience.

The addInput Function

The addInput function is one of the main components of this feature. It is an asynchronous function that takes a string parameter called newText. This text represents the new task that the user wants to add to the list. Before sending the information to the server, I check if the text is not empty. This is crucial to avoid storing invalid entries in the database.

async function addInput(newText: string) {
  // Checks if the text is not empty
  if (newText.trim() === "") {
    return;
  }
  const newInput = {
    newtext: newText,
    isChecked: false
  };

  try {
    const response = await fetch("https://yoururl.com/tasks", {
      method: 'POST',
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(newInput)
    });

    if (!response.ok) {
      throw new Error(`Error: ${response.statusText}`);
    }

    SetInput(""); // Clears the input field after successful submission

  } catch (error) {
    console.error("Error adding tasks:", error);
  }
  listInput(); // Updates the displayed task list
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation

  1. Text Verification: I start by checking if the newText string is empty or contains only whitespace. If so, the function returns immediately, saving unnecessary operations.

  2. Creating the newInput Object: Next, I create a newInput object with the task and a boolean indicator isChecked, initially set to false.

  3. Sending the Request: I use the fetch function to send an HTTP POST request to the server. The header settings indicate that I’m sending JSON data.

  4. Handling the Response: After sending the request, I check if the server’s response is successful. If not, I throw an error to handle the failure appropriately.

  5. Clearing and Updating: After a successful submission, I call SetInput("") to clear the input field and listInput() to update the task list on the interface.

Auxiliary Functions

In addition to addInput, two auxiliary functions play crucial roles in the interface:

SetInput

The SetInput function clears the text input field after adding a new task. This ensures that the field is empty and ready for new entries. It is usually used in conjunction with React state to control the value of the input field.

function SetInput(value: string) {
  setInputValue(value); // Updates the input value state
}
Enter fullscreen mode Exit fullscreen mode

listInput

The listInput function is responsible for updating and rendering the task list in the user interface. By fetching tasks from the server, I ensure that any changes are immediately reflected in the interface.

async function listInput() {
  try {
    const response = await fetch("https://yoururl.com/tasks");
    if (!response.ok) {
      throw new Error(`Error: ${response.statusText}`);
    }
    const tasks = await response.json();
    setTasks(tasks); // Updates the task list state
  } catch (error) {
    console.error("Error listing tasks:", error);
  }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

These functions work in harmony to provide a smooth and efficient user experience in my task list application. Implementing this logic taught me a lot about managing state and asynchronous interactions.

I hope this example can serve as inspiration or a starting point!!

localstorage Article's
30 articles in total
Favicon
É seguro guardar dados do usuário no localStorage?
Favicon
Understanding Local Storage and Session Storage in JavaScript
Favicon
How to Make localStorage Data Reactive
Favicon
Enhance React Native Security and Performance: with MMKV Storage
Favicon
# Storing Data in the Database with JavaScript
Favicon
Efficient Data Management in Manufacturing: Leveraging localStorage in Angular
Favicon
Beginner's Guide to Web Scraping and Proxy Setup with JavaScript
Favicon
Securing Web Storage: LocalStorage and SessionStorage Best Practices
Favicon
Javascript Ls/ss/cookies
Favicon
Javascript Ls/ss/cookies
Favicon
Javascript Ls/ss/cookies😎
Favicon
Faking sessionStorage to keep sites from crashing
Favicon
Elevating Data Integrity in Your React Application with Converters in Storage Management
Favicon
Storing and Testing State in localStorage with React
Favicon
Local Storage in 5 mins: A Beginner’s Guide to Cookies, localStorage, and sessionStorage
Favicon
Mastering LocalStorage Management with React Hooks
Favicon
Utilizing Local Storage in React Components: A Comprehensive Guide
Favicon
Working with JavaScript Local Storage
Favicon
LocalStorage with React Hooks
Favicon
Learn Local Storage in React: Create a Light and Dark Theme Switcher Application
Favicon
Lokalnotes - onBrowser notesapp
Favicon
Local Storage vs Session Storage in JavaScript
Favicon
Cookies vs Local Storage vs Session Storage
Favicon
How to show a pop-up only once with React, localStorage and Material UI modal
Favicon
Local Storage Bookmark Manager
Favicon
Mongez Cache, a powerful storage manager for web applications
Favicon
Using the Local Storage API in React: Creating a custom hook component
Favicon
-
Favicon
彻底弄清楚session,cookie,sessionStorage,localStorage的区别及应用场景(面试向)
Favicon
Must have Custom hooks for NextJs

Featured ones: