B
B
bzotsss2021-09-06 15:00:26
React
bzotsss, 2021-09-06 15:00:26

Why does react throw an error?

Hello, I'm trying to return an object from a custom hook and at the same time it gives an error

Error: Objects are not valid as a React child (found: object with keys {title, first, last}). If you meant to render a collection of children, use an array instead.

Here is the code:
import { useState, useEffect } from "react";

export const useContacts = () => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isError, setIsError] = useState(false);

  useEffect(() => {
    const getContacts = async () => {
      try {
        setIsLoading(true);
        const response = await fetch("https://randomuser.me/api/?results=10");
        const { results, error } = await response.json();
        console.log(results);
        if (error) {
          throw new Error(error);
        }
        setData(results);
      } catch (e) {
        setIsLoading(false);
        setIsError(false);
      } finally {
        setIsLoading(false);
      }
    };
    getContacts();
  }, []);
  return {
    data,
    isLoading,
    isError,
  };
};

Please tell me what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question