0

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;

1 Answer 1

1

You have already initialized post as an array of object conatining n number of different posts

Reassigning its value to just one post inside handleClick will cause posts to loose it's initial state

So just create another hook that will be an empty string initially and will get a different random post from array posts after every click!

Something like this:

import React, { useEffect, useState } from "react";

import "./App.css";

function App() {
  const [posts, setPosts] = useState([]);
  const [onePost, setOnePost] = useState(''); //one more hook for storing current random post

  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)];
    setOnePost(random);//value assigned here
  };
  console.log(posts);
  return (
    <div>
      <button onClick={handleClick}>Click me</button>
      <span>{onePost.quote}</span> //print onePost instead of Post
    </div>
  );
}

export default App;
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.