# Storing Data in the Database with JavaScript

michaelmoranis

Michael Moranis

Posted on August 10, 2024

# 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!!

💖 💪 🙅 🚩
michaelmoranis
Michael Moranis

Posted on August 10, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related