Assume i have the following state
const [page, setPage] = useState(1);
here i have a function that does api call then some operation on the state i.e
const getProducts=async()=>{
// i use the page state in an api call
...
//then afterward update the state
setPage(page 1);
}
and I have a function Refresh that reset the State to initial value and calls the getProducts function
const Refresh =()=>{
setState(1)
getProducts()
}
the issue is when i call the refresh function the page state is not reset/updated and hence the api call is called with the page i don't want. What is the Error here and how do i go about it.Thanks in advance
CodePudding user response:
Add the getProducts
a parameter that would allow you to state the page (currentPage
). If you pass currentPage
it's used in the setState
. If not, it sets page 1
:
const [page, setPage] = useState(1);
const getProducts = async(currentPage)=>{
// i use the page state in an api call
...
//then afterward update the state
setPage(currentPage ?? page 1);
}
const Refresh = () =>{
getProducts(1)
}
React has a way to avoid batching states, but this effects the render of the JSX, and not the values inside the callback, for example:
const { useState } = React
const { flushSync, createRoot } = ReactDOM
const Demo = () => {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
const inc = () => {
flushSync(() => {
setA(a 1)
})
setB(a)
console.log(a)
}
return (
<div>
<button onClick={inc}>Increment</button>
<div>a {a} - {b} b</div>
</div>
)
}
createRoot(root).render(<Demo />)
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root"></div>