Home > other >  Unable to display entries: TypeError: Cannot read properties of undefined (reading 'map')
Unable to display entries: TypeError: Cannot read properties of undefined (reading 'map')

Time:12-16

I am trying to display some entries from the backend. If I pass data through Postman, the data is perfectly passed to the database. However, I'm unable to display them in the frontend. Here's my code

export default function EntriesDisplay() {

    const [entry,setEntry] = useState([]);
    const [update, setUpdate] = useState(false);

useEffect(function() {
        fetch("http://localhost:8000/api/entries")
        .then((res) => {
            console.log(res.data);
            setEntry(res.data)
        })
        .catch((err)=>{
            console.log(err);
        })
    }, [update])

return(
        <>
                <ul className="list-container">
                    {entry.map((data) => (
                        <EntriesCard
                            data={data}
                            handleEdit={handleEdit}
                            handleDelete={handleDelete}
                        />
                    ))}
                </ul>

Here's the component EntriesCard

function EntriesCard({data, handleEdit, handleDelete}) {
    const{_id, title, link, description} = data;

    return(
        <li key={_id}>
            <div className="title-description">
                <h3>{title}</h3>
                <h2>{link}</h2>
                <p>{description}</p>
            </div>
            <div className="button-container">
                <button className="button" name={_id} onClick={handleEdit}>
                    Edit
                </button>
                <button className="button" name={_id} onClick={handleDelete}>
                    Delete
                </button>
            </div>
        </li>
    )
}

Here's the backend of the code

app.get('/api/entries', asyncHandler(async (req, res) => {
    const entries = await Entry.find();
    res.json(entries);
})
)

CodePudding user response:

Ok, thanks for confirming what the response is. It is JSON so you need to "unpack" that. Assuming the JSON data is still the array you need to store in state, check for ok response and return the response.json() Promise and continue chaining.

useEffect(function() {
  fetch("http://localhost:8000/api/entries")
    .then(response => {
      if (!response.ok) throw new Error("response not ok");
      return response.json();
    })
    .then((data) => {
      console.log(data);
      setEntry(data);
    })
    .catch((err)=>{
      console.log(err);
    });
}, [update]);

CodePudding user response:

You should use res.json() to parse the returned json data.

useEffect(function() {
    fetch("http://localhost:8000/api/entries")
    .then(res => res.json())
    .then((data) => {
        console.log(data);
        setEntry(data)
    })
    .catch((err)=>{
        console.log(err);
    })
}, [update])
  • Related