When to use a hook

Hi there

I am doing the advanced RN course and while I was in Chapter 14 (Posting Data) of Networking module, I came across with the question below.

In chapter 11 Mosh introduced the concept of useHook to call API (GET request) and since it’s not littering the codebase with duplicate code for invoking APIs, I thought it’s a great idea to extend the same hook method to invoke a differnt API (POST request).

the useAPI.js code is below

import { useState } from "react";

export default useAPI = (apiFunc) => {
  const [data, setData] = useState([]);
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(false);

  const request = async (...args) => {
    setLoading(true);
    const response = await apiFunc(...args);
    setLoading(false);

    if (!response.ok) {
      return setError(response.problem);
    }

    setError(false);
    setData(response.data);
  };

  // expose request function outside the hook so components can call it.
  // we also need to expose the state variables in our component
  return { data, error, loading, request };
};

Now my question is why this is not the preferred approach when doing a POST request.

Instead of reusing the code from the above hook, Mosh invoked it directly whereas I wrote the following code.

const {
    data: formData,
    error,
    loading,
    request: create,
  } = useAPI(listings.newListing);

  const submitListing = (values) => {
    // console.log(values.images[0]);
    const data = new FormData();

    data.append("title", values.title);
    data.append("price", values.price);
    data.append("categoryId", values.category.value);
    data.append("description", values.description);
    values.images.forEach((image, index) => {
      data.append("images", {
        name: "image -" + index,
        type: "image/jpeg",
        uri: image,
      });
    });
    data.append("location", JSON.stringify(location));
    create(data);
    if (error) {
      alert("An error occured while creating a new listing");
      console.log("Error occured", error);
    }
  };

  return (
    <Screen>
      <Formik
        initialValues={{
          title: "",
          price: "",
          description: "",
          category: null,
          images: [],
        }}
        onSubmit={(values) => submitListing(values)}
        validationSchema={validationSchema}
      >

listings is from listings.js and has the following code

import client from "./client";

const endpoint = "/listings";

const getListings = () => client.get(endpoint);

const newListing = (formData) => client.post(endpoint, formData);

export default {
  getListings,
  newListing,
};

Is there a norm that while submitting a form it’s not ideal to use a hook and prefer to make an async call instead?

Thanks for your response in advance.

Prad

Overall this looks okay to me! I’m wondering about this part…

create(data);
if (error) {
  alert("An error occured while creating a new listing");
  console.log("Error occured", error);
}

Is it possible that if (error) is executed before the create function is finished? If so I’m wondering if you need to something like create(data).then(() => { if (error) etc... }) or use async/await.