I am having an issue where my page doesn't refresh when I call the refresh function I passed.
function ProductsPage(props) {
const [products, setProduct] = useState([])
const [shouldRefresh, setRefresh] = useState(false)
function refreshProducts() {
setRefresh(!shouldRefresh)
}
const token = localStorage.getItem("token")
const headers = { Authorization: "Token " token }
useMemo(() => (axios.get("/products", { headers: headers }).then((resp) => (
setProduct(resp.data)
))
), shouldRefresh)
return (
<Box className="cardDeck">
<Redirect_if_not_logged_in />
{products.map((product) => (
<InfoCard product={product} refresh={refreshProducts}></InfoCard>
)).reverse()}
</Box>
)
}
Whenever I call props.refresh()
from the InfoCard, nothing happens.
CodePudding user response:
You will need to use useEffect hook instead of useMemo
function ProductsPage(props) {
const [products, setProduct] = useState([]);
const [shouldRefresh, setRefresh] = useState(false);
function refreshProducts() {
setRefresh(!shouldRefresh);
}
const token = localStorage.getItem("token");
const headers = {
Authorization: "Token " token,
};
useEffect(() => {
axios
.get("/products", {
headers: headers,
})
.then((resp) => setProduct(resp.data));
}, [shouldRefresh]);
return (
<Box className="cardDeck">
<Redirect_if_not_logged_in />
{products
.map((product) => (
<InfoCard product={product} refresh={refreshProducts}></InfoCard>
))
.reverse()}
</Box>
);
}
CodePudding user response:
The shouldRefresh in useMemo, should be in a dependancy array like this:
useMemo(() => (axios.get("/products", { headers: headers }).then((resp) => (
setProduct(resp.data)
))
), [shouldRefresh])
Also I don`t think you need useMemo here, useEffect would do the same thing