0

I'm playing around with react hooks and following the tutorail at https://www.valentinog.com/blog/hooks/. I put in the empty array as the second argument following the docs and some reason I'm still getting an infinite loop.

import React, { useState, useEffect } from "react";
export default function useDataLoader() {
  const [data, setData] = useState([]);
  useEffect(() => {
    fetch("http://api.icndb.com/jokes/random")
      .then(response => response.json())
      .then(data => {
        setData(data.value.joke)
        console.log(data)
      }, []);
  });
  return (
    <div>
      <div>
        {data}
      </div>
    </div>
  );
}


import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Hook from './components/Hook'
import DataLoader from './components/DataLoader'

class App extends Component {
  render() {
    return (
      <div className="App">
        <Hook />
        <DataLoader/>
      </div>
    );
  }
}

export default App;
1
  • 1
    Take a look at my answer here: stackoverflow.com/questions/53059059/… (note that the other answers including the accepted answer are a bit outdated... mine is updated...) Let me know if you have questions... Commented Mar 24, 2019 at 21:24

1 Answer 1

2

The [] is in the wrong place. You pass it to fetch().then() instead of useEffect

  useEffect(() => {
    fetch("http://api.icndb.com/jokes/random")
      .then(response => response.json())
      .then(data => {
        setData(data.value.joke)
        console.log(data)
      });
  }, []);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.