Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

reactjs - I'M GETTING TypeError: records.map is not a function in my react app

I'm getting this error:

TypeError: records.map is not a function FROM MY Records.js file

Please what am I doing wrong in my code?

Here's my app.js:

const App = () => {
  const [records, setRecords] = useState([])
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    const fetchRecords = async () => {
        setLoading(true)
        const res = await fetch('http://api.enye.tech/v1/challenge/records')
        const data  = await res.json();
        setRecords(data)
        setLoading(false)
      } 
     fetchRecords()
     // eslint-disable-next-line
  }, []) 

  console.log(records);
  
    return (
      <Fragment>
        <SearchBar />
        <div className='container'>
          <h2>Records Firstnames</h2>
          <Records loading={loading} records={records} />
        </div>
      </Fragment>
    );
  }

I'm rendering the fetched data from this Records.js file:

const Records = ({ records, loading }) => {
if(loading) {
    return <Preloader />
}
    return <ul className='collection mb-4'>
             {records && records.map(record => (
                <li key={record.id} className='collection-item'>
                    {record.FirstName}
                    {record.LastName}
                </li>
             ))}

            </ul>

}

This is the API I'm fetching from:

enter image description here

question from:https://stackoverflow.com/questions/65652173/im-getting-typeerror-records-map-is-not-a-function-in-my-react-app

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to go to the array portion of the api reponse (records), otherwise the data wil be an object ({}) which you cannot use .map on. the data.records.profiles will be an array ([]) and that will work with a .map function.

change you code to

useEffect(() => {
    const fetchRecords = async () => {
        setLoading(true)
        const res = await fetch('http://api.enye.tech/v1/challenge/records')
        const data  = await res.json();
        setRecords(data.records.profiles)
        setLoading(false)
      } 
     fetchRecords()
     // eslint-disable-next-line
  }, []) 

also check that the records are not loading

 {!loading ? <Records records={records} /> : <></>}

You might also want to change the state name to 'profiles' and not records because you are only using the profiles portion on the reponse


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...