DEV Community

Cover image for Use Firebase? localStorage? Or both?
kebin20
kebin20

Posted on

Use Firebase? localStorage? Or both?

During my coding journey, creating this app allowed me to put into practice all the concepts I have learned. Specifically, I took the opportunity to become more proficient in using styled components and React Router, two essential tools for React development.

As I developed the app, one of the most significant challenges I encountered was determining the best way to store flashcard data and track their state. The purpose of the app was to help students revise vocabulary they had learned since third grade from their textbooks.

Initially, I considered uploading every single flashcard to Firebase. However, I soon realized that this approach would be overly complicated and burdensome. Additionally, it would require each student to create a registered account and log in, which would create significant hassle, especially since the app's goal was to be simple and straightforward.

After exploring various options, I decided to use localStorage as the most accessible and straightforward solution for students to track their flashcard revision progress. The main master deck would be stored in Firebase and only be accessible to teachers.

Implementing the Firebase feature presented a challenge since I was not very familiar with the technology. However, I eventually succeeded in uploading the master deck to Firebase and retrieving the main data. This achievement was one of the project's highlights.

 /* Upload initial data to Firebase */
  function writeFlashcardData(decks: FlashcardSetData[]) {
    const db = getDatabase();
    set(ref(db, 'flashcards'), {
      decks,
    });
  }

  /* Fetching flashcard from Firebase*/
  const fetchFlashcardHandler = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const response = await fetch(
        'https://english-flashcards-app-962bb-default-rtdb.asia-southeast1.firebasedatabase.app/flashcards.json'
      );
      if (!response.ok) {
        throw new Error('An error has occurred');
      }

      const data = await response.json();
      setDeck(data.decks);

      // Obtain all of the cards arrays, join them and flatten it
      const decksArr = [];
      for (let i = 0; i < data.decks.length; i++) {
        decksArr.push(data.decks[i].cards);
      }
      const flattenedDecksArr = decksArr.flat();
      setAllCards(flattenedDecksArr);
    } catch (error: any) {
      setError(error.message);
    }
    setIsLoading(false);
  }, []);

  useEffect(() => {
    if (deck.length === 0) {
      writeFlashcardData(deckData);
      fetchFlashcardHandler();
    }
  }, [deck.length]);
Enter fullscreen mode Exit fullscreen mode

Hoping to implement user authentication for the teachers to login in the future using Firebase!

Top comments (0)