Una saga épica sobre un pequeño gancho personalizado para React (generadores, sagas, rxjs)

parte 2. Generadores





Preludio

La tarea consistía en implementar un precargador con una cuenta atrás de la reactancia. Porque No sé cómo buscar en Google y me gusta mucho esculpir bicicletas (un buen biplaza resultó ser de dos bicicletas "Ucrania"), entonces estaba condenado a profundizar en los campos del asincronismo. Me adelantaré y diré que implementé este precargador usando generadores, redux-saga, rxjs. Una experiencia muy interesante y me gustaría compartirla, dado que en el transcurso de los procedimientos, aparte de artículos que describen las cosas obvias y fragmentos de información puramente específica sobre stackoverflow, no encontré.





Entonces: parte uno: crear un gancho personalizado.





Estructura del precargador

Como escala del indicador de carga, elegí la cantidad de imágenes en el sitio (también puede seleccionar otros recursos), porque en mi caso, estos fueron los recursos más pesados ​​en la página.





Porque Tuve que hacer esto en la reacción, luego, por supuesto, lo diseñé en forma de un gancho personalizado y lo llamé usePreloader.





Código de precargador en sí
import React from "react";

export default function Preloader() {
  return (
    <div className="preloader__wrapper">
      <div className="preloader">
        <svg
          width="300"
          height="300"
          viewBox="0 0 300 300"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="M300 150C300 232.843 232.843 300 150 300C67.1573 300 0 232.843 0 150C0 67.1573 67.1573 0 150 0C232.843 0 300 67.1573 300 150ZM20.7679 150C20.7679 221.373 78.6271 279.232 150 279.232C221.373 279.232 279.232 221.373 279.232 150C279.232 78.6271 221.373 20.7679 150 20.7679C78.6271 20.7679 20.7679 78.6271 20.7679 150Z"
            fill="#F3F3F3"
          />
          <path
            d="M289.616 150C295.351 150 300.037 154.655 299.641 160.376C297.837 186.392 289.275 211.553 274.72 233.336C258.238 258.003 234.811 277.229 207.403 288.582C179.994 299.935 149.834 302.906 120.736 297.118C91.6393 291.33 64.9119 277.044 43.934 256.066C22.9561 235.088 8.66999 208.361 2.88221 179.264C-2.90558 150.166 0.0649254 120.006 11.4181 92.5975C22.7712 65.1886 41.9971 41.7618 66.6645 25.2796C88.4468 10.725 113.608 2.16293 139.624 0.359232C145.345 -0.0374269 150 4.64906 150 10.384C150 16.1189 145.343 20.7246 139.627 21.1849C117.723 22.9486 96.5686 30.2756 78.2025 42.5475C56.9504 56.7477 40.3864 76.931 30.6052 100.545C20.8239 124.159 18.2647 150.143 23.2511 175.212C28.2375 200.28 40.5457 223.307 58.6191 241.381C76.6926 259.454 99.7195 271.762 124.788 276.749C149.857 281.735 175.841 279.176 199.455 269.395C223.069 259.614 243.252 243.05 257.453 221.797C269.724 203.431 277.051 182.277 278.815 160.373C279.275 154.657 283.881 150 289.616 150Z"
            fill="#6CAE30"
          />
        </svg>
      </div>
      <div className="preloader__counter">0%</div>
    </div>
  );
}

      
      







Estilos de precargador
.App {
  font-family: sans-serif;
  text-align: center;
}

.preloader__wrapper {
  position: fixed;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  z-index: 2000;
}

.preloader {
  position: relative;
  width: 18.75rem;
  height: 18.75rem;
}
.preloader svg {
  width: 18.75rem;
  height: 18.75rem;
  -webkit-animation: spin 4s infinite linear;
  animation: spin 4s infinite linear;
}
.preloader__counter {
  margin-top: 1.625rem;
  padding-left: 1rem;
  font-family: sans-serif;
  font-size: 3.125rem;
  line-height: 1;
  color: #6cae30;
}

@media (max-width: 900px) {
  .preloader {
    width: 6.25rem;
    height: 6.25rem;
  }
  .preloader svg {
    width: 6.25rem;
    height: 6.25rem;
  }
  .preloader__counter {
    margin-top: 0.75rem;
    padding-left: 0.5rem;
    font-size: 2.125rem;
  }
}

@-moz-keyframes spin {
  from {
    -moz-transform: rotate(0deg);
  }
  to {
    -moz-transform: rotate(360deg);
  }
}
@-webkit-keyframes spin {
  from {
    -webkit-transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
  }
}
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

      
      







Implementación del gancho

La lógica del gancho es buscar todas las etiquetas <img> en la página y adjuntar controladores para los eventos de carga y error. Esto se hace usando el siguiente código





const updateCounter = () => {
  dispatch({
    type: ACTIONS.SET_COUNTER,
    data: state.counter + state.counterStep
  });
};

const checkImageLoading = (url) => {
  const imageChecker = new Image();
  imageChecker.addEventListener("load", updateCounter);
  imageChecker.addEventListener("error", updateCounter);
  imageChecker.src = url;
};
      
      



El gancho tendrá un estado, que almacenará el paso del indicador y el estado actual del indicador. En esta (primera) parte, el precargador se implementa solo usando react hooks, pero en varias versiones. No conectaremos redux para almacenar el estado, porque este es un gancho personalizado y me gustaría reutilizarlo en el futuro.





Código fuente de Js
export const SET_COUNTER = "SET_COUNTER";
export const SET_COUNTER_STEP = "SET_COUNTER_STEP";
export const initialState = {
  counter: 0,
  counterStep: 0,
};
export const reducer = (state, action) => {
  switch (action.type) {
    case SET_COUNTER:
      return { ...state, counter: action.data };
    case SET_COUNTER_STEP:
      return { ...state, counterStep: action.data };
    default:
      throw new Error("This action is not applicable to this component.");
  }
};

export const ACTIONS = {
  SET_COUNTER,
  SET_COUNTER_STEP,
};

      
      







Opción 1 (no funciona, para mayor claridad). useReducer

, , useRef . checkImageLoading state .





usePreloader.js
import { useReducer, useEffect } from "react";
import { reducer, initialState, ACTIONS } from "./state";

const PRELOADER_SELECTOR = ".preloader__wrapper";
const PRELOADER_COUNTER_SELECTOR = ".preloader__counter";

const usePreloader = () => {
  const [state, dispatch] = useReducer(reducer, initialState);

  const preloaderEl = document.querySelector(PRELOADER_SELECTOR);
  const counterEl = document.querySelector(PRELOADER_COUNTER_SELECTOR);

  const updateCounter = () => {
    dispatch({
      type: ACTIONS.SET_COUNTER,
      data: state.counter + state.counterStep
    });
  };

  const checkImageLoading = (url) => {
    const imageChecker = new Image();
    imageChecker.addEventListener("load", updateCounter);
    imageChecker.addEventListener("error", updateCounter);
    imageChecker.src = url;
  };

  useEffect(() => {
    const imgArray = document.querySelectorAll("img");
    if (imgArray.length > 0) {
      dispatch({
        type: ACTIONS.SET_COUNTER_STEP,
        data: Math.floor(100 / imgArray.length) + 1
      });
      imgArray.forEach((img) => {
        checkImageLoading(img.src);
      });
    }
  }, []);

  useEffect(() => {
    if (counterEl) {
      state.counter < 100
        ? (counterEl.innerHTML = `${state.counter}%`)
        : hidePreloader(preloaderEl);
    }
  }, [state]);

  return;
};

const hidePreloader = (preloaderEl) => {
  preloaderEl.remove();
};

export default usePreloader;
      
      







2. useReducer + useRef

, useRef . state .





:





//   state
const stateRef = useRef(state);
      
      



state current stateRef:





const updateCounter = () => {
  dispatch({
    type: ACTIONS.SET_COUNTER,
    data: stateRef.current.counter + stateRef.current.counterStep //    state,   stateRef
  });
};
      
      



state





stateRef.current.counter < 100
	? (counterEl.innerHTML = `${stateRef.current.counter}%`) //    state,   stateRef
	: hidePreloader(preloaderEl);
      
      



state, :





useEffect(() => {
  stateRef.current = state; //   state,     state
  ...
}, [state]);
      
      



useReducer + useRef
import { useReducer, useEffect, useRef } from "react";
import { reducer, initialState, ACTIONS } from "./state";

const PRELOADER_SELECTOR = ".preloader__wrapper";
const PRELOADER_COUNTER_SELECTOR = ".preloader__counter";

const usePreloader = () => {
  const [state, dispatch] = useReducer(reducer, initialState);

  //   state
  const stateRef = useRef(state);

  const preloaderEl = document.querySelector(PRELOADER_SELECTOR);
  const counterEl = document.querySelector(PRELOADER_COUNTER_SELECTOR);

  const updateCounter = () => {
    dispatch({
      type: ACTIONS.SET_COUNTER,
      data: stateRef.current.counter + stateRef.current.counterStep //    state,   stateRef
    });
  };

  const checkImageLoading = (url) => {
    const imageChecker = new Image();
    imageChecker.addEventListener("load", updateCounter);
    imageChecker.addEventListener("error", updateCounter);
    imageChecker.src = url;
  };

  useEffect(() => {
    const imgArray = document.querySelectorAll("img");
    if (imgArray.length > 0) {
      dispatch({
        type: ACTIONS.SET_COUNTER_STEP,
        data: Math.floor(100 / imgArray.length) + 1
      });
      imgArray.forEach((img) => {
        checkImageLoading(img.src);
      });
    }
  }, []);

  useEffect(() => {
    stateRef.current = state; //   state,     state
    if (counterEl) {
      stateRef.current.counter < 100
        ? (counterEl.innerHTML = `${stateRef.current.counter}%`) //    state,   stateRef
        : hidePreloader(preloaderEl);
    }
  }, [state]);

  return;
};

const hidePreloader = (preloaderEl) => {
  preloaderEl.remove();
};

export default usePreloader;

      
      







. ( network devtools), . , . ..





useEffect(() => {
  ...
}, [state]);
      
      



state. stateRef.current . .





, useEffect useLayoutEffect:





  useLayoutEffect(() => {
    stateRef.current = state;
    if (counterEl) {
      stateRef.current.counter < 100
        ? (counterEl.innerHTML = `${stateRef.current.counter}%`)
        : hidePreloader(preloaderEl);
    }
  }, [state]);
      
      



.





useEffect - . .. - state .





useLayoutEffect - . .. .





: , , useLayoutEffect; , - useEffect.





3. useState + useRef

useReducer, .. : . useState. couterStep :





  const [counterStep, setCounterStep] = useState(0);
  const counterStepStateRef = useRef(counterStep);
  const setCounterStepState = (data) => {
    counterStepStateRef.current = data;
    setCounterStep(data);
  };
      
      



useState + useRef
import { useEffect, useLayoutEffect, useRef, useState } from "react";

const PRELOADER_SELECTOR = ".preloader__wrapper";
const PRELOADER_COUNTER_SELECTOR = ".preloader__counter";

const usePreloader = () => {
  const [counter, setCounter] = useState(0);
  const counterStateRef = useRef(counter);
  const setCounterState = (data) => {
    counterStateRef.current = data;
    setCounter(data);
  };

  const [counterStep, setCounterStep] = useState(0);
  const counterStepStateRef = useRef(counterStep);
  const setCounterStepState = (data) => {
    counterStepStateRef.current = data;
    setCounterStep(data);
  };

  const preloaderEl = document.querySelector(PRELOADER_SELECTOR);
  const counterEl = document.querySelector(PRELOADER_COUNTER_SELECTOR);

  const updateCounter = () => {
    setCounterState(counterStateRef.current + counterStepStateRef.current);
  };

  const checkImageLoading = (url) => {
    const imageChecker = new Image();
    imageChecker.addEventListener("load", updateCounter);
    imageChecker.addEventListener("error", updateCounter);
    imageChecker.src = url;
  };

  useEffect(() => {
    const imgArray = document.querySelectorAll("img");
    if (imgArray.length > 0) {
      setCounterStepState(Math.floor(100 / imgArray.length) + 1);
      imgArray.forEach((img) => {
        checkImageLoading(img.src);
      });
    }
  }, []);

  useLayoutEffect(() => {
    if (counterEl) {
      counterStateRef.current < 100
        ? (counterEl.innerHTML = `${counterStateRef.current}%`)
        : hidePreloader(preloaderEl);
    }
  }, [counter, counterStep]);
  return;
};

const hidePreloader = (preloaderEl) => {
  preloaderEl.remove();
};

export default usePreloader;

      
      











export default function App() {
  usePreloader();
  return (
    <div className="App">
      <Preloader />
      ...
    </div>
  );
}
      
      







:

:









  • useReducer useState





  • useRef





  • diferencia en el comportamiento de los componentes cuando se utilizan los ganchos useEffect y useLayoutEffect









Enlace de zona de pruebas





Enlace de repositorio





Este podría ser el final, porque el gancho funciona. Pero este precargador resultó inesperadamente ser un gran ejemplo para trabajar con el flujo de eventos y su procesamiento asincrónico. Por tanto, la diversión comienza en la siguiente parte.





Empecemos, o más bien sigamos, con generadores ...
















All Articles