TanStackT
TanStack2y ago
4 replies
dead-brown

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
Was this page helpful?