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;