When I call fetchProducts I want productPage state to be updated before it runs the next line of code since the next line requires the updated state.
The state only gets updated after the function has finished running. No matter where in the fetchProducts function I put console.log(productPage) it returns the state as it was before the function was called.
const [productPage, setProductPage] = useState(1)
const [displayProducts, setDisplayProducts] = useState([])
const fetchProducts = async () => {
setProductPage(productPage + 1) // DOES NOT UPDATE UNTIL AFTER FUNCTION RUNS
const newProductsData = await fetch(`/api/getproducts?page=${productPage}`)
const newProductsArr = await newProductsData.json()
setDisplayProducts(displayProducts.concat(newProductsArr))
}
Is this possible? I've found workarounds to the problem but it feels hacky and not ideal.
I'm using next.js also, I'm not sure if that would make a difference. I can't use normal variables as they reset on each render.