Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React 17: "useEffect has missing dependencies" with useMutation function

I'm learning react query and the following code is working as expecting but I have this warning message:

React Hook useEffect has missing dependencies: 'code' and 'mutate'. Either include them or remove the dependency array.eslintreact-hooks/exhaustive-deps

But if I add 'code' and 'mutate' in the dependency array I have an infinite loop.

import React, { useState, useEffect } from "react";
import { useMutation } from "react-query";
import * as api from "../api/api";

const getQuery = () => {
  const queryParams = new URLSearchParams(window.location.search);
  return queryParams.get("code");
};

const Authentication = () => {
  const [code] = useState(getQuery());

  useEffect(() => {
    if (code) {
      mutate.mutate(code);
    }
  }, []);

  const auth = async () => {
    window.location.href = `https://www.betaseries.com/authorize?client_id=${process.env.REACT_APP_API_KEY}&scope=&redirect_uri=${process.env.REACT_APP_API_URL_CALLBACK}`;
  };

  const mutate = useMutation(api.access_token, {
    onSuccess: (data) => {
      localStorage.setItem("isAuth", data.data.access_token);
    },
  });

  return <button onClick={auth}>Login</button>;
};

export default Authentication;

Short explanation of what I did:

  1. User click on login button, he is redirected to the website to enter his login / password
const auth = async () => {
    window.location.href = `https://www.betaseries.com/authorize?client_id=${process.env.REACT_APP_API_KEY}&scope=&redirect_uri=${process.env.REACT_APP_API_URL_CALLBACK}`;
  };
  1. After a success login he is redirected to my website with a url params ?code=xxx

  2. I catch the code and use it to call a route that will provide me his access_token

  useEffect(() => {
    if (code) {
      mutate.mutate(code);
    }
  }, []);
like image 968
jeyremd Avatar asked Nov 18 '25 01:11

jeyremd


1 Answers

The mutate function itself is stable, but the object returned from useMutation is not. If you destruct, you can add it to your dependency array:

const { mutate } = useMutation(…)
like image 63
TkDodo Avatar answered Nov 20 '25 14:11

TkDodo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!