I created a REST API and fetched the data within a useEffect hook. I stored that data in a state called posts and wanted to display a random value from that state and display when someones click a button. Every time a user clicks the button I want it to display a different value. Everything works until I click the button a second time and then it pops up an error saying posts are undefined. Below is the entire component. I need help with making that error going away because I expect a new post to appear every time a user clicks the button.
import React, { useEffect, useState } from "react";
import "./App.css";
function App() {
const [posts, setPosts] = useState([]);
useEffect(() => {
const fetchPosts = async () => {
try {
const fetchingPosts = await fetch("http://localhost:5000/posts");
const posts = await fetchingPosts.json();
setPosts(posts);
} catch (err) {
console.log(err);
}
};
fetchPosts();
}, []);
const handleClick = () => {
const random = posts[Math.floor(Math.random() * posts.length)];
setPosts(random);
};
console.log(posts);
return (
<div>
<button onClick={handleClick}>Click me</button>
<span>{posts.quote}</span>
</div>
);
}
export default App;