DEV Community

Cover image for 24- React File Manager Chapter XXIV: Completing Create Directory Action
Hasan Zohdy
Hasan Zohdy

Posted on

24- React File Manager Chapter XXIV: Completing Create Directory Action

Now everything is prepared to make our createDirectory action work properly.

Let's add our toast to the createDirectory action.

// src/store/actions/file-manager/createDirectory.ts
import { toastLoading } from "design-system/components/Toast";
import Kernel from "../Kernel";
import fileManagerService from "../services/file-manager-service";

export default function createDirectory(kernel: Kernel) {
  return function create(
    directoryName: string,
    directoryPath: string = kernel.currentDirectoryNode?.path as string,
  ) {
    return new Promise((resolve, reject) => {
      const loader = toastLoading(
        "Creating directory...",
        "We are creating your directory, please wait a moment.",
      );
      fileManagerService
        .createDirectory(directoryName, directoryPath)
        .then(response => {
          loader.success("Success!", "Your directory has been created.");

          resolve(response.data.node);
        })
        .catch(error => {
          loader.error("Error", error.response.data.error);
          reject(error);
        });
    });
  };
}
Enter fullscreen mode Exit fullscreen mode

So we returned a new promise to be able to use it in the component, and we used the toastLoading function to show a loading toast, and then we used the fileManagerService to make the request to the server, then we used the loader to show a success toast if the request was successful, and an error toast if the request failed.

Once the request is done, we'll resolve the promise with the newly created directory node then close the directory modal.

// CreateDirectoryModal.tsx

import { Modal } from "@mantine/core";
import { Form, FormInterface } from "@mongez/react-form";
import SubmitButton from "design-system/components/Form/SubmitButton";
import TextInput from "design-system/components/Form/TextInput";
import React from "react";
import { useKernel } from "../../../hooks";

export type CreateDirectoryModalProps = {
  open: boolean;
  onClose: () => void;
};

export default function CreateDirectoryModal({
  open,
  onClose,
}: CreateDirectoryModalProps) {
  const kernel = useKernel();

  const submitForm = (e: React.FormEvent, form: FormInterface) => {
    const directoryName = form.value("name");

    kernel.actions
      .createDirectory(directoryName)
      // 👇🏻 close the modal after creating the directory
      .then(() => {
        onClose();
      })
      // 👇🏻 If an error occurred, then allow form to be resubmitted again for example to allow the user to change the directory name.
      .catch(() => {
        form.submitting(false);
      });
  };

  return (
    <Modal
      title={<strong>{kernel.currentDirectoryNode?.path}</strong>}
      opened={open}
      trapFocus={false}
      onClose={onClose}>
      <Form onSubmit={submitForm}>
        <h2>Create New Directory</h2>
        <TextInput
          name="name"
          required
          autoFocus
          placeholder="Please Enter Directory Name"
        />

        <div
          style={{
            textAlign: "end",
            marginTop: "1.5rem",
          }}>
          <SubmitButton>Create</SubmitButton>
        </div>
      </Form>
    </Modal>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now what we added here is a then call to close the modal as there is no longer a need for it, and we added a catch call to allow the user to resubmit the form in case of an error.

Kernel Nodes Tree

Now we need to add the newly created directory to the given path children tree.

But before this step we need to create a large tree to contain all of our files and directories.

This will allow us to easily find the given path and add the newly created directory to it.

Next Chapter

In the next chapter we'll make a tree based kernel to inject all of our nodes inside it.

Article Repository

You can see chapter files in Github Repository

Don't forget the main branch has the latest updated code.

Tell me where you are now

If you're following up with me this series, tell me where are you now and what you're struggling with, i'll try to help you as much as i can.

Salam.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay