samedi 20 août 2022

How to perform action or render component before/after every http request in React?

I want to know if there is a way to create a kind of middleware in React?

What i want is to have an alert component show if there is a failing result for an http request.

Right now, i am making http request on login,registration,etc and i am importing my alert component in every page and setting the Alert component props like type, message, visibility everywhere i need the component, but i think maybe there is a better way of doing this.

Here is my code:


...imports

export const RegisterPage = () => {

  const [alertConfig, setAlertConfig] = useState({
    type: "",
    message: "",
    show: false,
  });

...code

const onSubmitHandler = async (e) => {
    e.preventDefault();
    if (!isFormValid()) return;

    const formData = new FormData();

    formData.append("password", formValues.password);
    if (formValues.provider.startsWith("8")) {
      formData.append("contact", formValues.provider);
    } else {
      formData.append("email", formValues.provider);
    }

    setIsLoading(true);
    try {
      const response = await fetch(
        `${process.env.REACT_APP_API_URL}/auth/register`,
        {
          method: "POST",
          body: formData,
        }
      );

      const data = await response.json();

      if (data.status === "success") {
        const { token, user } = data.data;

        dispatch(setCurrentUser(user, token));

        navigate("/choose-actor");
      } else {
        setAlertConfig({
          type: "warning",
          message: data.message,
          show: true,
        });
      }
    } catch (error) {
      console.log(error);
      setAlertConfig({
        type: "danger",
        message: "Ocorreu algum erro",
        show: true,
      });
    } finally {
      setIsLoading(false);
    }
  };
return 
    ...html
        {alertConfig.show && <Alert {...alertConfig} />}
    ...more html

As you can see, i am changing the configuration for the alert inside inside the function that executes the http request, and i have to do the save for every page that performs this action.

I looking for a design patter where i dont have to repeat myself.

Hope my question is clear.

Aucun commentaire:

Enregistrer un commentaire