reactjsrestful-authentication

Error Coming in UI but response coming correct in console


Here is my code for fetching notes using ContextAPI to pass the function between components:

const [notes, setNote] = useState([]);

let GETchallNotes = async () => { 
  let response = await fetch(`${host}/api/notes/fetchNotes`, {
    method: "GET",
    headers: {
      "Content-Type":"application/json",
      "auth-token":authtoken,
    },
  });
  const json = await response.json(); 
  console.log(json);
  setNote(json);
};

return (
  <NoteContext.Provider
    value={{ notes, deleteNote, addNote, updateNote, GETchallNotes }}
  >
    {props.children}
  </NoteContext.Provider>
);

In my Note component, I am using useEffect to trigger the GETchallNotes function. However, even though the notes are properly being fetched and logged to the console, I am experiencing a UI error. Here is my Note component:

import React, { useEffect } from 'react';
import { useContext } from 'react';
import NoteContext from '../context/NoteContext';
import NoteItem from './NoteItem';
import AddNote from './AddNote';

function Note() {
  const provider=useContext(NoteContext)
  const {notes, GETchallNotes}=provider;

  useEffect(()=>{
    console.log("Triggered")
    GETchallNotes();
  },[]);

  return (
    <>
      <AddNote></AddNote>
      <div className='row my-3'>
        <h2>Your Notes</h2>  
        {notes.map((item) => {
          return <NoteItem note={item}></NoteItem>
        })}
      </div>
    </>
  );
}

export default Note

You can see image here What could be causing this UI error, and how can I fix it?


Solution

  • According to your screenshot it seems that the value that is being returned from the API you're calling is an object with a key notes that has the value of the list of notes that you're looking for.

    The reason you're getting the error is that an object doesn't allow the function map.

    Here is the revised code:

    const [notes, setNote] = useState([]);
    
    let GETchallNotes = async () => { 
      let response = await fetch(`${host}/api/notes/fetchNotes`, {
        method: "GET",
        headers: {
          "Content-Type":"application/json",
          "auth-token":authtoken,
        },
      });
      const json = await response.json(); 
      console.log(json);
      setNote(json?.notes ?? []);
    };
    
    return (
      <NoteContext.Provider
        value={{ notes, deleteNote, addNote, updateNote, GETchallNotes }}
      >
        {props.children}
      </NoteContext.Provider>
    );