DEV Community

Touhidul Shawan
Touhidul Shawan

Posted on

Better Pattern in fetching API data?

I am fetching jokes data on the first time component rendered in useEffect hooks. But after that, I want to get new jokes data when the Want more button will be clicked, so I am handling that in handleNewJoke function. But here is the problem I am repeating same code. What approch should I take here?

import * as React from "react";
import { useState, useEffect } from "react";
import axios from "axios";
import Jokes from "./components/Jokes";

export interface JokesProp {
  id: number;
  type: string;
  setup: string;
  punchline: string;
}

const App: React.FC = () => {
  const [jokes, setJokes] = useState<JokesProp>({
    id: 166,
    type: "general",
    setup: "What did one wall say to the other wall?",
    punchline: "I'll meet you at the corner!",
  });

  useEffect(() => {
    const getJokes = async () => {
      const response = await axios.get(
        "https://official-joke-api.appspot.com/random_joke"
      );
      setJokes(response.data);
    };
    getJokes();
  }, []);

  const handleNewJokes = async () => {
    const response = await axios.get(
      "https://official-joke-api.appspot.com/random_joke"
    );
    setJokes(response.data);
  };

  return (
    <main>
      <h1>Jokes</h1>
      <Jokes jokes={jokes} />
      <button onClick={handleNewJokes}>want more</button>
    </main>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
bryceamcdaniel profile image
BryceAMcDaniel

Can you not do this?

useEffect(() => {
handleNewJokes();
}, []);

This should call the arrow function after your component has mounted.

Collapse
 
touhidulshawan profile image
Touhidul Shawan

Haha 😀. This was simple. Thank you. I always think of easy things in complicated way

Collapse
 
bryceamcdaniel profile image
BryceAMcDaniel

No problem! Good luck!