DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Md. Touhidul Islam Shawan
Md. Touhidul Islam 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
Md. Touhidul Islam Shawan Author

Haha πŸ˜€. This was simple. Thank you. I always think of easy things in complicated way

Collapse
bryceamcdaniel profile image
BryceAMcDaniel

No problem! Good luck!

Find what you were looking for? Sign up so you can:

Β 
🌚 Enable dark mode
πŸ”  Change your default font
πŸ“š Adjust your experience level to see more relevant content