How to avoid useEffect for render twice?
Hi,
my react query version: ^4.29.25
so I have pseudocode below
my objective is, i want to insert some data use mutation to DB when the data is not exist in useEffect, but the query is running twice in development mode. I was try to prevent using useState.. but not work.
how to fix that?
const [isMutationExecuted, setIsMutationIsExecuted] = useState(false)
useEffect(() => {
if (isMutationExecuted) return
const data = fetchDataFromApi()
const payload; // the payload just string
if (data === null) {
insertData.mutate(payload)
setIsMutationIsExecuted(true)
}
}, [])
thanks
4 Replies
flat-fuchsia•16mo ago
Hello there.
useEffect
may run 2-3 times in development due to a StrictMode
https://react.dev/reference/react/useEffect#my-effect-runs-twice-when-the-component-mountsuseEffect – React
The library for web and native user interfaces
flat-fuchsia•16mo ago
Synchronizing with Effects – React
The library for web and native user interfaces
harsh-harlequin•16mo ago
Why are you using this state and not useMutation.status ?
unwilling-turquoiseOP•16mo ago
hi guys, thanks for your response..
the problem solved when I add option "enable" in useQuery