简体   繁体   中英

React useEffect Cannot read property 'map' of undefined

 import { handleResponse, handleError } from "./apiUtils"; const baseUrl = process.env.REACT_APP_API_URL; export function getAllNotes() { return fetch(baseUrl + "/notes", { method: "GET", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }).then(res =>res.json()).then(data=>console.log(data)) }

 export async function handleResponse(response) { if (response.ok) return response.json(); if (response.status === 400) { // So, a server-side validation error occurred. // Server side validation returns a string error message, so parse as text instead of json. const error = await response.text(); throw new Error(error); } throw new Error("Network response was not ok."); } // In a real app, would likely call an error logging service. export function handleError(error) { // eslint-disable-next-line no-console console.error("API call failed. " + error); throw error; }

I am trying to learn react functional components and get comfortable with React Hooks. I am importing a function from a Api.js page and running it inside useEffect. The function is supposed to hit my back end which retrieves data from mongo Atlas and sends it up to my front end to be mapped. The data is an array of 4 objects. I am unable to map it because when the component renders the test variable is undefined. I have struggled to understand this for a long time. This would be a huge help and please explain in a not so technical way I struggle understanding very technical terms. Thank you!

 import React, {useState, useEffect} from 'react'; import {getAllNotes} from '../api/authorApi' function CourseList(props) { const [test, setTest] =useState([]) useEffect(()=>{ getAllNotes().then(_test=> setTest(_test)) }, []); return ( <table className="table"> <thead> <tr> <th>Title</th> <th>Author ID</th> <th>Category</th> </tr> </thead> <tbody> {test.map(course => { return ( <tr key={course.user_id}>hi </tr> ); })} </tbody> </table> ); }

There is little change, you have to return a promise.

Sample code:

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

const getNotes = () => {
  return new Promise (
    (resolve, reject) => 
   fetch('https://jsonplaceholder.typicode.com/todos')
   .then(data => resolve(data.json()))
   .catch(err => reject(err))
   )  
}

const ToDos = () => {
  const [toDos, setToDos] = useState([]);
  
  useEffect(() => {
    getNotes().then( data => setToDos(data))
  }, []);

  const renderData = () => toDos.map((toDo) => <li>title: { toDo.title } </li>)
  return (
    <Fragment>
      <ul>
      {renderData()}
      </ul>
    </Fragment>
  )
}

export default ToDos;

In your case there is nothing returned from the function getNotes after completion of an API call, hence the test is undefined, as a result it breaks down to an error: Cannot read property 'map' of undefined .

working code snippet: https://codesandbox.io/s/react-playground-forked-bwt89?file=/ToDoSample.jsx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM