Back to Hooks

useFileSystemAccess

useFileSystemAccess.tsx

useFileSystemAccess

UTILITY

// Open/save real files with the File System Access API; returns readFile, writeFile, and live permission state

Quick Usage

const { readFile, writeFile, saveFile, hasPermission } = useFileSystemAccess();

Features

File System API
Permission Management
Read/Write Files
Browser Support

When to Use

Perfect for text editors, file managers, data export/import tools, or any app requiring direct file system access.

Interactive Example

❌ File System Access API is not supported in this browser. Try Chrome, Edge, or another Chromium-based browser.

Complete Example

import { useFileSystemAccess } from '@usegrand/react-hokss';

function FileEditor() {
  const { 
    readFile, 
    writeFile, 
    saveFile, 
    hasPermission, 
    isSupported, 
    isLoading, 
    error 
  } = useFileSystemAccess();

  const [content, setContent] = useState('');

  const handleOpenFile = async () => {
    const fileContent = await readFile({
      types: [{
        description: 'Text files',
        accept: { 'text/plain': ['.txt', '.md'] }
      }]
    });
    if (fileContent) setContent(fileContent);
  };

  const handleSaveFile = async () => {
    await saveFile(content, 'document.txt', {
      types: [{
        description: 'Text files',
        accept: { 'text/plain': ['.txt'] }
      }]
    });
  };

  if (!isSupported) {
    return <div>File System Access API not supported</div>;
  }

  return (
    <div>
      <div className="toolbar">
        <button onClick={handleOpenFile} disabled={isLoading}>
          Open File
        </button>
        <button onClick={handleSaveFile} disabled={isLoading || !content}>
          Save File
        </button>
        <span>Permission: {hasPermission ? '✅' : '❌'}</span>
      </div>
      
      <textarea
        value={content}
        onChange={(e) => setContent(e.target.value)}
        placeholder="Open a file or start typing..."
        rows={20}
        cols={80}
      />
      
      {error && <div className="error">Error: {error}</div>}
    </div>
  );
}

API Reference

Parameters

Returns

FileSystemAccessState

Object containing file system access state and functions

isSupported

Boolean indicating if File System Access API is supported

hasPermission

Boolean indicating if write permission is granted

isLoading

Boolean indicating if file operation is in progress

error

Error message if operation failed

fileHandle

Current file handle reference

readFile

Function to read a file from disk

writeFile

Function to write to currently opened file

saveFile

Function to save content to a new/existing file

openFile

Function to open and read a file (alias for readFile)

requestPermission

Function to request file system permissions

clearError

Function to clear the current error state