useCallback function issue in react

25 Views Asked by At

In this code, the searchText is showing in the console from outside of the handleFetchExams function. Why searchText value is not coming inside the handleFetchExams function? Please help me to bring the searchText value inside the handleFetchExams function. Thank you.

const [state, dispatch] = useReducer(reducer, initialState);
const { products, browseProductsQueryParams } = state;
const { searchText } = browseProductsQueryParams;
const { sort, level, filter, page } = state;
console.log(searchText);

 const handleFetchExams = useCallback(
async ({ reset }: { reset: boolean }) => {
  console.log(searchText);
  dispatch({ type: productCatalogActions.SET_LOADING, payload: true });
  dispatch({ type: productCatalogActions.SET_ERROR, payload: false });
  try {
    let query = "";
    if (searchText.length > 0) {
      query = `${query}&search=${searchText.toLowerCase()}`;
    }
    query = `${query}&sort=${sort}&level=${level}&filter=${filter}&page=${
      reset ? 1 : page
    }`;

    const data = await fetchExamsByLevel(query);
    dispatch({
      type: productCatalogActions.SET_DATA,
      payload: {
        quizzes: data.quizzes,
        endOfResults: data.quizzes.length < 12,
      },
    });
    return data;
  } catch (error) {
    dispatch({ type: productCatalogActions.SET_ERROR, payload: true });
  } finally {
    dispatch({ type: productCatalogActions.SET_LOADING, payload: false });
  }
},
[sort, level, filter, page, searchText]);
0

There are 0 best solutions below