Home > database >  Uncaught TypeError: users.map is not a function - REACT
Uncaught TypeError: users.map is not a function - REACT

Time:12-16

Please can someone help me look at this REACT code to see why i am getting the error "Uncaught TypeError: users.map is not a function". I have checked online and couldn't get an answer that is why i am posting something that looks like a question that has been asked before. Please help. See code here:

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

const url = 'https://api.github.com/users';

const UseEffectFetchData = () => {
  const [users, setUsers] = useState([]);

  const getUsers = async () => {
    const result = await fetch(url)
    const Usrs = result.json()
    setUsers(Usrs)
  }

  useEffect(() => {
    getUsers();
  }, []);

  return (
    <>
      <h3>github users</h3>
      <ul className='users'>
        {
          users.map((user) => {
            const { id, login, avatar_url, html_url } = user;
            return (
              <li key={id}>
                <img src={avatar_url} alt={login} />
                <div>
                  <h4>{login}</h4>
                  <a href={html_url}>profile</a>
                </div>
              </li>
            );
          })
        }
      </ul>
    </>
  );
};

export default UseEffectFetchData;

CodePudding user response:

You forgot to add “await” here:

const Usrs = await result.json()

Best regards!

CodePudding user response:

In this case:

result.json() will return a promise.

you should use await to get json.

const getUsers = async () => {
  const result = await fetch(url)
  const Usrs = await result.json()
  setUsers(Usrs)
}
  • Related