Search code examples
reactjstypescriptmaterial-uijson-server

Property '' does not exist on type 'never'. (useState on mapped JSON server data using Typescript)


I am following a react tutorial on mui and decided to incorporate typescript

for reference: Net ninja MUI

Notes.tsx

fetched JSON server data then set it to notes

import React, { useEffect, useState } from 'react';

const Notes = () => {
  const [notes, setNotes] = useState([]);

  useEffect(() => {
    fetch('http://localhost:8000/notes')
      .then((res) => res.json())
      .then((data) => setNotes(data));
  }, []);

Mapped the JSON Server dummy data here

  return (
    <div>
      {notes.map((note:string) => (
        <p key={note.id}>{note.title}</p>
      ))}
    </div>
  );
};

export default Notes;

db.json (JSON server dummy data)

{
  "notes": [
    {
      "title": "Yoshi's birthday bash",
      "details": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",
      "category": "reminders",
      "id": 1
    },
    {
      "title": "Complete my ninja training",
      "details": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took.",
      "category": "work",
      "id": 2
    },
    {
      "title": "Order a pizza!",
      "details": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",
      "category": "todos",
      "id": 3
    }
  ]
}

This is the Error that occurs


Solution

  • You need to type your notes object and tell your component local state to expect that as well as your map function, see below for some pointers.

    import React, { useEffect, useState } from 'react';
    
    type Note = {
     title: string,
     details: string,
     category: "reminders" | "work" | "todos",
     id: number,
    }
    
    const Notes = () => {
      const [notes, setNotes] = useState<Note[]>([]);
    
      useEffect(() => {
        fetch('http://localhost:8000/notes')
          .then((res) => res.json())
          .then((data: Note[]) => setNotes(data));
      }, []);
    
     return (
        <div>
          {notes.map((note: Note) => (
            <p key={note.id}>{note.title}</p>
          ))}
        </div>
      );
    };
    
    export default Notes;