Home > Net >  Trying to run cutomized hook, used this api "https://type.fit/api/quotes". I'm able t
Trying to run cutomized hook, used this api "https://type.fit/api/quotes". I'm able t

Time:11-10

I am a newbie in react and here I am trying to work on customized hooks. I AM using this API "https://type.fit/api/quotes" the problem I'm facing is that, not getting any errors, neither getting any quotes in my outputs. please help me to find and understand what is wrong

function App() {
  const [quote, setQuote]=useState();
  useEffect(() => {
    const fetchQuote =async()=>{
      await fetch("https://type.fit/api/quotes")
        .then(
          (response)=>response.json())
        .then(
          (data)=>{setQuote(data.value)});
          // console.log(text);
      }
    fetchQuote();
  }, [])
  return (
    <div>
      <h1>Random Quotes</h1>
      <p>{quote}</p>
      <button>Click For Random Quotes</button>
    </div>
  );
}

CodePudding user response:

The response is an array

// 20211109225522
// https://type.fit/api/quotes

[
  {
    "text": "Genius is one percent inspiration and ninety-nine percent perspiration.",
    "author": "Thomas Edison"
  },
  {
    "text": "You can observe a lot just by watching.",
    "author": "Yogi Berra"
  },
  {
    "text": "A house divided against itself cannot stand.",
    "author": "Abraham Lincoln"
  },
  ...

so data.value is undefined, just store data in state and render appropriately.

function App() {
  const [quotes, setQuotes] = useState([]);

  useEffect(() => {
    const fetchQuote = async () => {
      await fetch("https://type.fit/api/quotes")
        .then((response) => response.json())
        .then((data) => setQuotes(data));
    };
    fetchQuote();
  }, []);

  return (
    <div>
      <h1>Random Quotes</h1>
      <ul>
        {quotes.map(({ author, text }, index) => (
          <li key={index}>
            "{text}" ~{author}
          </li>
        ))}
      </ul>
      <button>Click For Random Quotes</button>
    </div>
  );
}

Edit trying-to-run-cutomized-hook-used-this-api-https-type-fit-api-quotes-im-a

enter image description here

  • Related