Ishan jain
Ishan jain

Reputation: 169

onSuccess not triggered when query has staleTime. react-query

I have a Form component whose initial data I am setting like so:

 const EditProfileForm: React.FC = ({ section }) => {

    const [state, dispatch] = useReducer(
        updateProfileReducer,
        PROFILE_INITIAL_STATE,
    );

    const setInitalState = (getApiData: GetUserDetailsQueryResp) => {
        dispatch(
            updateProfileAction({
                data: getApiData.getUserDetails,
                reset: getApiData.getUserDetails,
            }),
        );
    };

   const { data, isLoading } = useGetUserDetailsQuery(setInitalState);
    
   const onChange = (formData) => {
    // update the state by dispatching the data
  }

   return // My component;
}

The useGetUserDetailsQuery has a staleTime set for 1 hour. The stale time is used since, its a User data. The user query is used at multiple places in App and I don't want to use to fetch it from the server again and again.

The problem is the onSuccess callback doesn't trigger when query has staleTime, thus not setting my initialState.

Any way to avoid this problem (without using useEffect) ?

the query function for reference:

export const useGetUserDetailsQuery = (
    onSuccess?: (stateData: GetUserDetailsQueryResp) => void,
): UseQueryResult<GetUserDetailsQueryResp, ErrorResponse> => {
    return useGraphqlQuery('get-user-details', GET_USER_DETAILS, {
        staleTime: 600000,
        onSuccess: onSuccess,
    });
};

Upvotes: 0

Views: 2038

Answers (1)

TheWuif
TheWuif

Reputation: 1036

onSuccess is only triggered when a request is send, but you can use a workaround like this:

const EditProfileForm: React.FC = ({ section }) => {
  
  const initDispatched = useRef(false);
  const [state, dispatch] = useReducer(
    updateProfileReducer,
    PROFILE_INITIAL_STATE,
  );

  const setInitalState = (getApiData: GetUserDetailsQueryResp) => {
    dispatch(
      updateProfileAction({
        data: getApiData.getUserDetails,
        reset: getApiData.getUserDetails,
      }),
    );
  };

  const { data, isLoading } = useGetUserDetailsQuery(setInitalState);
  
  useEffect(() => {
    if(data && !initDispatched.current) {
      initDispatched.current = true;
      setInitalState(data);
    }
  }, [data])
  
  const onChange = (formData) => {
    // update the state by dispatching the data
  }

  return // My component;
}

Upvotes: 0

Related Questions