Bird
Raised Fist0
React Nativemobile~20 mins

File system access in React Native - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
File System Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate
2:00remaining
Reading a file content in React Native
What will be the output shown on the screen after running this React Native code snippet that reads a file content asynchronously?
React Native
import React, { useEffect, useState } from 'react';
import { Text, View } from 'react-native';
import * as FileSystem from 'expo-file-system';

export default function App() {
  const [content, setContent] = useState('');

  useEffect(() => {
    async function readFile() {
      const fileUri = FileSystem.documentDirectory + 'test.txt';
      await FileSystem.writeAsStringAsync(fileUri, 'Hello React Native');
      const data = await FileSystem.readAsStringAsync(fileUri);
      setContent(data);
    }
    readFile();
  }, []);

  return (
    <View>
      <Text>{content}</Text>
    </View>
  );
}
AThe screen is blank with no text
BThe screen displays: [object Promise]
CThe screen displays: Hello React Native
DThe app crashes with a runtime error
Attempts:
2 left
💡 Hint
Remember that reading files asynchronously returns a Promise, so you must await it before setting state.
📝 Syntax
intermediate
1:30remaining
Correct syntax for writing a file in React Native
Which option shows the correct syntax to write the string 'Data saved' to a file named 'output.txt' using Expo FileSystem in React Native?
Aawait FileSystem.writeFileAsync('output.txt', 'Data saved');
BFileSystem.writeFile(FileSystem.documentDirectory + 'output.txt', 'Data saved');
CFileSystem.writeAsString(FileSystem.documentDirectory + 'output.txt', 'Data saved');
Dawait FileSystem.writeAsStringAsync(FileSystem.documentDirectory + 'output.txt', 'Data saved');
Attempts:
2 left
💡 Hint
Check the exact method name and parameters in Expo FileSystem documentation.
❓ lifecycle
advanced
1:30remaining
File read timing in React Native component lifecycle
In which React Native lifecycle phase is it best to read a file asynchronously to ensure the UI updates with the file content after the component mounts?
AInside useEffect with an empty dependency array []
BInside useEffect with no dependency array
CDirectly inside the component body before return
DInside the constructor function
Attempts:
2 left
💡 Hint
Think about when side effects like file reading should happen in React functional components.
🔧 Debug
advanced
1:30remaining
Debugging file read error in React Native
You run this code but get an error: "File does not exist" when reading a file. What is the most likely cause?
React Native
const fileUri = FileSystem.documentDirectory + 'notes.txt';
const content = await FileSystem.readAsStringAsync(fileUri);
console.log(content);
AThe file 'notes.txt' was never created or written before reading
BYou must import 'fs' module to read files in React Native
CreadAsStringAsync requires a callback function as second argument
DThe fileUri path is incorrect because documentDirectory is undefined
Attempts:
2 left
💡 Hint
Check if the file exists before reading it.
🧠 Conceptual
expert
2:00remaining
Understanding file system permissions on mobile devices
Which statement best describes file system access permissions in React Native apps on iOS and Android?
AApps can freely read and write any file anywhere on the device without restrictions
BApps have sandboxed storage areas and need explicit permissions to access external storage on Android
CiOS allows apps to write files anywhere on the device but Android restricts to app folders only
DReact Native automatically grants all file system permissions without user consent
Attempts:
2 left
💡 Hint
Think about mobile OS security and app sandboxing.

Practice

(1/5)
1. What is the main purpose of using react-native-fs in a React Native app?
easy
A. To read and write files on the device's file system
B. To create user interface components
C. To manage app navigation between screens
D. To handle network requests and API calls

Solution

  1. Step 1: Understand the role of react-native-fs

    This library is designed to provide file system access in React Native apps.
  2. Step 2: Identify the correct functionality

    It allows reading and writing files on the device, unlike UI or network libraries.
  3. Final Answer:

    To read and write files on the device's file system -> Option A
  4. Quick Check:

    File system access = read/write files [OK]
Hint: Remember: react-native-fs is for file operations only [OK]
Common Mistakes:
  • Confusing file system access with UI components
  • Thinking it manages navigation or network calls
  • Assuming it handles permissions automatically
2. Which of the following is the recommended ES6 import syntax for react-native-fs in a React Native file?
easy
A. import * as RNFS from 'react-native-fs';
B. import RNFS from 'react-native-fs';
C. import { RNFS } from 'react-native-fs';
D. const RNFS = require('react-native-fs');

Solution

  1. Step 1: Recall ES6 import syntax for default exports

    react-native-fs exports a default object, so use import RNFS from 'react-native-fs';.
  2. Step 2: Check other options

    const RNFS = require('react-native-fs'); uses CommonJS require (valid but less common in modern React Native). import { RNFS } from 'react-native-fs'; incorrectly destructures. import * as RNFS from 'react-native-fs'; imports all as namespace but is not the recommended style here.
  3. Final Answer:

    import RNFS from 'react-native-fs'; -> Option B
  4. Quick Check:

    Default import syntax = import RNFS from 'react-native-fs'; [OK]
Hint: Use default import for react-native-fs: import RNFS from '...' [OK]
Common Mistakes:
  • Using destructuring import for default export
  • Mixing require and import styles
  • Using namespace import unnecessarily
3. What will the following code output if the file test.txt contains the text "Hello World"?
import RNFS from 'react-native-fs';

RNFS.readFile(RNFS.DocumentDirectoryPath + '/test.txt', 'utf8')
  .then(contents => console.log(contents))
  .catch(err => console.log('Error:', err.message));
medium
A. Error: File not found
B. An empty string
C. undefined
D. "Hello World"

Solution

  1. Step 1: Understand readFile behavior

    The readFile method reads the file content as a string when encoding is 'utf8'.
  2. Step 2: Check file content and output

    The file contains "Hello World", so the promise resolves and logs this string.
  3. Final Answer:

    "Hello World" -> Option D
  4. Quick Check:

    readFile with utf8 returns file text [OK]
Hint: readFile with 'utf8' returns file text content [OK]
Common Mistakes:
  • Assuming readFile returns a buffer or object
  • Expecting error if file exists
  • Ignoring promise and expecting synchronous output
4. Identify the error in this code snippet that tries to write text to a file:
import RNFS from 'react-native-fs';

RNFS.writeFile('/path/to/file.txt', 'Sample text', 'utf8')
  .then(() => console.log('File written'))
  .catch(error => console.log('Write error:', error));
medium
A. The file path should use RNFS.DocumentDirectoryPath or similar, not an absolute string
B. The encoding 'utf8' is not supported by writeFile
C. writeFile does not return a promise
D. The text argument must be an object, not a string

Solution

  1. Step 1: Check file path usage

    In React Native, absolute paths like '/path/to/file.txt' are invalid; use RNFS.DocumentDirectoryPath or similar directory constants.
  2. Step 2: Validate other parameters

    Encoding 'utf8' is valid, writeFile returns a promise, and text can be a string.
  3. Final Answer:

    The file path should use RNFS.DocumentDirectoryPath or similar, not an absolute string -> Option A
  4. Quick Check:

    Use RNFS paths, not absolute strings [OK]
Hint: Always use RNFS directory constants for file paths [OK]
Common Mistakes:
  • Using absolute file paths directly
  • Misunderstanding writeFile return type
  • Passing wrong data types for text
5. You want to save user notes in a file and then read them back later. Which approach correctly handles permissions, writes the file, and reads it back safely in React Native using react-native-fs?
hard
A. Use fetch API to write and read files on device storage
B. Write file directly to '/storage/emulated/0/notes.txt' without permission, then read it
C. Request storage permission, write file using RNFS.DocumentDirectoryPath, then read file with error handling
D. Write file with no encoding specified, then read file with 'ascii' encoding

Solution

  1. Step 1: Handle permissions properly

    On mobile devices, storage permission must be requested before file operations.
  2. Step 2: Use safe file paths and encoding

    Use RNFS.DocumentDirectoryPath for file location and specify encoding like 'utf8' for writing and reading.
  3. Step 3: Implement error handling

    Use promises with then and catch to handle success and errors safely.
  4. Final Answer:

    Request storage permission, write file using RNFS.DocumentDirectoryPath, then read file with error handling -> Option C
  5. Quick Check:

    Permissions + RNFS paths + error handling = Request storage permission, write file using RNFS.DocumentDirectoryPath, then read file with error handling [OK]
Hint: Always request permission and use RNFS paths with error handling [OK]
Common Mistakes:
  • Skipping permission requests
  • Using hardcoded absolute paths
  • Ignoring promise errors
  • Using wrong encoding for text files
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard