5

I used useEffect in my component in order to execute an async function.

 useEffect(() => {
    scoreRequest(answers);
  }, [answers]);

Then I get this warning:

React Hook useCallback has a missing dependency: 'scoreRequest'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

I used the useCallback to avoid this warning:

const getScore = useCallback(() => {
  scoreRequest(answers);
  }, [answers]);

  useEffect(() => {
    scoreRequest(answers);
  }, [answers]);

But still got the same error. However, I found a similar question and it's mentioned in the answer either to declare the function into the useEffect or I could disable the rule. The function scoreRequest() declared in another file and I don't want to mix it with my component.

export const scoreRequest = (answers: IAnswer[]): ThunkAction<void, AppState, null, Action<string>> => {
  return async (dispatch: Dispatch) => {
    dispatch(startScoreRequest());
    getScoreApi(answers).then((response: AxiosResponse) => {
      const { data } = response;
      const answer = {
        scoreLabel: data.message,
        userScore: data.result.userScore,
        totalScore: data.result.totalScore,
        emoji: data.result.emoji,
        scoreLabelColor: data.result.scoreLabelColor
      };
      dispatch(successScore(answer));
    }, (error: AxiosError) => {
      let errorMessage = "Internal Server Error";
      if (error.response) {
        errorMessage = error.response.data.error;
      }
      dispatch(failScore(errorMessage));
      dispatch(errorAlert(errorMessage));
    });
  };
};

Is it any solution to fix this warning?

Slim
  • 5,527
  • 13
  • 45
  • 81

0 Answers0