skip to Main Content

I’m working on a React application where I’m trying to display a list of notes. The notes are fetched from an API and stored in a state variable using useState. However, when I try to map over the notes state to render them, I keep getting the error:

"TypeError: notes.map is not a function"

I checked my initial state and it is set to an empty array. Here’s the relevant code:

import "./App.css";
import React, { useState, useEffect } from "react";

type Note = {
  id: number;
  title: string;
  content: string;
};

const App = () => {
  const [notes, setNotes] = useState<Note[]>([]);

  useEffect(() => {
    const fetchNotes = async () => {
      try {
        const response = await fetch("http://localhost:5000/api/notes");
        const notes: Note[] = await response.json();
        setNotes(notes);
      } catch (e) {
        console.log(e);
      }
    };
    fetchNotes();
  }, []);

  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [selectedNote, setSelectedNote] = useState<Note | null>(null);

  const handleAddNote = (event: React.FormEvent) => {
    event.preventDefault();
    const newNote: Note = {
      id: notes.length + 1,
      title: title,
      content: content,
    };
    setNotes([...notes, newNote]);
    setTitle("");
    setContent("");
  };

  const handleNoteClick = (note: Note) => {
    setSelectedNote(note);
    setTitle(note.title);
    setContent(note.content);
  };

  const handleUpdateNote = (event: React.FormEvent) => {
    event.preventDefault();
    if (!selectedNote) return;

    const updateNote: Note = {
      id: selectedNote.id,
      title: title,
      content: content,
    };

    const updateNotesList = notes.map((note) =>
      note.id === selectedNote.id ? updateNote : note
    );

    setNotes(updateNotesList);
    setTitle("");
    setContent("");
    setSelectedNote(null);
  };

  const handleCancel = () => {
    setTitle("");
    setContent("");
    setSelectedNote(null);
  };

  const deleteNote = (event: React.MouseEvent, noteId: number) => {
    event.preventDefault();
    const updatedNotes = notes.filter((note) => note.id !== noteId);
    setNotes(updatedNotes);
  };

  return (
    <div className="app-container">
      <form
        className="note-form"
        onSubmit={(event) =>
          selectedNote ? handleUpdateNote(event) : handleAddNote(event)
        }
      >
        <input
          value={title}
          onChange={(event) => setTitle(event.target.value)}
          placeholder="Title"
          required
        ></input>
        <textarea
          value={content}
          onChange={(event) => setContent(event.target.value)}
          placeholder="Content"
          rows={10}
          required
        ></textarea>

        {selectedNote ? (
          <div className="edit-buttons">
            <button type="submit">Save</button>
            <button onClick={handleCancel}>Cancel</button>
          </div>
        ) : (
          <button type="submit">Add Note</button>
        )}
      </form>

      <div className="notes-grid">
        {notes.map((note) => (
          <div
            className="notes-items"
            key={note.id}
            onClick={() => handleNoteClick(note)}
          >
            <div className="notes-header">
              <button onClick={(event) => deleteNote(event, note.id)}>x</button>
            </div>
            <h2>{note.title}</h2>
            <p>{note.content}</p>
          </div>
        ))}
      </div>
    </div>
  );
};

export default App;

Any help would be appreciated.

I’ve tried debugging and logging the notes state, but the issue persists. The API response should be an array of notes, but I’m not sure why notes.map is throwing this error. What could be causing this problem?

2

Answers


  1. Chosen as BEST ANSWER

    thanks yall but i was able to come up with the solution. th problem was in how i was passing in the data to setNotes. I changed the useEffect to the code below and was able to get the notes successfully.

      useEffect(() => {
        const fetchNotes = async () => {
          try {
            const response = await fetch("http://localhost:5000/api/notes");
    
            const data = await response.json();
    
            // Log the fetched data
            console.log("Fetched notes:", data);
    
            // Ensure the data is an array of notes
            
            setNotes(data.notes);
          } catch (e) {
            console.log(e);
          }
        };
    
        fetchNotes();
      }, []);
    

  2. Check request response data and add check .map for array of notes

    {notes?.map((note) => ())}

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search