I need the useProductList
function to execute and finish all process before randomProduct
function will execute.
For some reason it doesnt work when fetchData
is a Promise so randomProduct
wont be executed.
I even tried without Promise
, nothing did work.
my custom hook
import { useState, useEffect } from "react";
export default function useProductList() {
const [productList, setProductObjsList] = useState([]);
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
let randomProducts = [];
const fetchData = () =>
new Promise(() => {
arr.splice(1, 7);
setProductObjsList(arr);
return arr;
});
const randomProduct = (productArr) => {
//some Math.random() and algorithm with the productArr
console.log("randomProduct()", productArr);
};
useEffect(() => {
fetchData().then((result) => randomProduct(result));
}, []);
return randomProducts;
}
I will be glad if someone will open my eyes and show me the right way of how to do it.
EDIT:
My original fetchData function
const fetchData = () =>
{
fetch('http://localhost:49573/WebService.asmx/ProductList')
.then((response) => response.text())
.then(
(xml) =>
new window.DOMParser().parseFromString(xml, 'text/xml')
.documentElement.firstChild.textContent
)
.then((jsonStr) => JSON.parse(jsonStr))
.then((data) => {
setProductObjsList(data);
})
});
randomProduct function
```const randomProduct = (productObjectList) => {
const products = [...productObjectList];
for (let index = 0; index < products.length; index++) {
let idx = Math.floor(Math.random() * products.length);
randomProducts.push(products[idx]);
products.splice(idx, 1);
}
};```