I'm trying to get info from an API as practice. I implemented 2 solutions to do so but only the first works.
1st (working solution):
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
dogs: {}
}
}
componentDidMount() {
get(< API URL here>)
.then(items => {
this.setState({ dogs: items.data.message })
})
.catch(err => {
console.log(err);
})
}
render() {
const { dogs } = this.state;
return (
<div>
<h1>Dog list</h1><br />
<p>The following is a list of dogs from the dog API provided:</p>
<div>
{Object.entries(dogs).map(([key, value]) => <p>{key}: {value}</p>)}
</div>
</div>
)
}
}
export default Home;
2nd (not-working):
const Home = () => {
const [dogs, setDogs] = useState({});
useEffect(() => {
get(< API URL here >)
.then(items => {
setDogs(items.data.message);
console.log(items.data.message);
})
.catch(err => {
console.log(err);
})
}, [])
return (
<div>
<h1>Home</h1>
<div>
{Object.entries(dogs).map(([key, value]) => {
<div>
<p>{key}</p>
</div>
})}
</div>
</div>
);
};
export default Home;
What am I doing wrong in the second instance? I'm trying to use this example to better understand the useEffect hook.