• 01-05-2023, 22:28:45
    #1
    Bu şekilde custom hooku bir component içinde kullanıyorum. Bu custom hookta allRecipes parametresine asenkron fetch ile api den dizi verisi çekiyorum. Daha sonra bu kod parçasından sonra bir fonksiyonda bu allRecipes değeri geldikten sonra belli komutların çalışması lazım ama uyguladığım async await çalışmıyor, allRecipes gelmeden komutlar çalışıyor.
    const [allRecipes, errorAllRecipes, isLoadingAllRecipes, allx] = useAllRecipes();
    Bu da çağırdığım yer; getRandomRecipe esasında bir buton, butona tıklandığında eğer allRecipes hala gelmemişse randomRecipeLoading devreye girer frontend için ve sonrasında await olarak allRecipes in gelmesiyle diğer komutlarda asenkron çalışır. Ama malesef asenkron yapısı çalışmıyor.
    const getRandomRecipe = async () => {
     console.log("getRandomRecipe clicked")
    if(allRecipes.length===0){
    
      dispatch({
        type: "RECIPE",
        payload: {
          randomRecipeLoading:true,
        },
      });
    }
    const recipesAll=await allRecipes.map(r=>r);
    const recipeSorted= await recipesAll?.sort(() => 0.5 - Math.random());;
    recipeSorted && dispatch({
      type: "RECIPE",
      payload: {
        randomRecipe:await recipeSorted[0],
        randomRecipeLoading:false,
        randomRecipeClick: true,
        searchRecipeClick: false,
      },
    });
      localStorage.setItem("random-recipe", JSON.stringify(recipeSorted[0]));
      navigate(`/random-recipes/${recipeSorted[0]?.id}`);
      };


    Bu da custom hook un bulunduğu dosya;
    import { useEffect, useReducer, useState, useRef } from "react";
    import RecipeReducer, { initialState } from "../reducers/RecipeReducer";
    const useAllRecipes = (configObj) => {
      const { axiosInstance, method, url, requestConfig = {} } = configObj;
      const [state, dispatch] = useReducer(RecipeReducer, initialState);
      const { allRecipes, errorAllRecipes, isLoadingAllRecipes } = state;
      const [isMounted, setIsMounted] = useState(false);
      const [allx, setAllx]=useState([])
      const [check, setCheck] = useState(false);
      const effectran = useRef(false);
    
      useEffect(() => {
        const controller = new AbortController();
        dispatch({
          type: "FETCH_START",
          payload: {
            //allRecipes:[],
            isLoadingAllRecipes: true,
            errorAllRecipes: "",
          },
        });
        if (effectran.current) {
          setIsMounted(true);
         
          const fetchAllRecipe = async () => {
            try {
              const response = await axiosInstance[method.toLowerCase()](url, {
                ...requestConfig,
                signal: controller.signal,
              });
              let res =await response.data;
              if(isMounted){
                setAllx(res) //burada bir de state ile deniyorum ama state ile return ettiğim de async çalışmıyor
                dispatch({
                  type: "FETCH_SUCCESS",
                  payload: {
                    allRecipes: res,
                  },
                });
              }
              //  isMounted &&
              //   dispatch({
              //     type: "FETCH_SUCCESS",
              //     payload: {
              //       allRecipes: res,
              //     },
              //   });
            } catch (err) {
               console.log(err)
              dispatch({
                type: "FETCH_ERROR",
                payload: {
                  errorAllRecipes: err.message,
                },
              });
            } finally {
              setCheck(allRecipes?.length === 0);
            !check && dispatch({
                type: "FETCH_FINALLY",
                payload: {
                  isLoadingAllRecipes: false,
                },
              });
             
            }
            
          };
           fetchAllRecipe();
        } else {
          effectran.current = true;
          setCheck(true);
        }
        return () => {
         // controller && controller.abort();
          setIsMounted(false);
        };
        //eslint-disable-next-line
      }, [check]);
        return  [allRecipes, errorAllRecipes, isLoadingAllRecipes, allx];
    
    }
    export default useAllRecipes;
  • 03-05-2023, 21:30:22
    #2
    Test etmedim ama şöyle bir şey denediniz mi,

    async function fetchAllRecipes() {
        const [allRecipes, errorAllRecipes, isLoadingAllRecipes, allx] = await useAllRecipes();
        console.log(allRecipes);
    }
    
    fetchAllRecipes();
  • 04-05-2023, 12:44:38
    #3
    maalesef custom hook u fonksiyon içerisinde yazamıyoruz. functional component içinde yazabiliriz ama onu da async yapamıyoruz.
    @Decentralized;