DEV Community

Discussion on: React useEffect fetching API

Collapse
lukeshiru profile image
LUKESHIRU

I recommend you take a look at React Query for this kind of stuff. They provide a bunch of useful functions and hooks to deal with API interactions and is way more robust than doing your own thing.
If you still want to do your own thing, I recommend to make some of your code more reusable, something like this:

/**
 * Curried fetch with JSON parsing.
 *
 * @template {Record<PropertyKey, unknown>} ResponseType
 * @param {RequestInit} init
 */
const fetchJSON =
    init =>
    /**
     * @param {RequestInfo} input
     * @returns {() => Promise<ResponseType>}
     */
    input =>
    () =>
        fetch(input, init).then(response => response.json());

// We use the curried function above to create a `getJSON` function
// from it, and we can set stuff like headers, auth, etc.
const getJSON = fetchJSON({ method: "GET" });

// We then create a getToDos function that will return
// a function that does the fetch with everything set...
const getToDos = getJSON("http://jsonplaceholder.typicode.com/todos");

// Finally, we use it:

const App = () => {
    const [todos, setTodos] = useState([]);

    useEffect(() => void getToDos().then(setTodos).catch(console.error), []);

    // ...
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
shubhamtiwari909 profile image
ShubhamTiwari909 Author

Thank you for this
I will try these things also