L
L
lucky42020-08-28 17:13:21
React
lucky4, 2020-08-28 17:13:21

How to display data with api backend?

There is a component where I want to display data from an existing api.
I tried to output data like this, purely in the console:

useEffect(() => {
    fetch('https://xxx')
    .then(response => response.json())
    .then(data => console.log(data))
  }, [])


Well, I already decided that this data would already be displayed in li-elements. BUT! Unfortunately, nothing happened, nothing outputs.
export default function ListItems() {
  const [users, setUsers] = useState(null)

  const URL = 'xxx'

  // const fetchData = async () => {
  //   const response = await axios.get(URL)
  //   setUsers(response.data)
  // }

  useEffect(() => async () => {
    const response = await axios.get(URL)
    setUsers(response.users)
  })

  return (
    <ul className="list">
      {
        users && users.map(user => {
          return (
            <li className="item" key={ user.id }>
              <img className="item__photo" src={ user.photo } alt="user-1"/>

              <div className="item__name">
                <h3 className="subtitle">{user.name}</h3>
              </div>

              <div className="item__description">
                <h3 className="description">{user.position}</h3>
                <h3 className="description">{user.email}</h3>
                <h3 className="description">{user.phone}</h3>
              </div>
            </li>
          )
        })
      }
    </ul>
  )
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Shcherbakov, 2020-08-28
@lucky4

useEffect(() => async () => {
    const response = await axios.get(URL)
    setUsers(response.users)
  })

You are returning a function, not using it.
You need something similar to this:
useEffect(() => {
    const fetchData = async () => {
      const response = await axios.get(URL);
      setUsers(response.users);
    };

    fetchData();
  }, []);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question