0

I am stuck with a React Context Provider where I define the state with useState and then want to pass current state values that I destructure from useState into a getSearchResults() utility function that constructs an API query string and returns a JSON object.

PROBLEM: all the destructured values go unnoticed by JS. When passed into the getSearchResults() function, searchText, pageNum and productsPerPage are all undefined. Can anyone help? Merci!

  const [searchText, setSearchText] = useState("");
  const [pageNum, setPageNum] = useState(1);
  const [productsPerPage, setproductsPerPage] = useState(10);

  const [searchResults, setSearchResults] = useState([]);

  const getSearchResults = (searchText, pageNum, productsPerPage) =>
    setSearchResults(fetchBeers(searchText, pageNum, productsPerPage));

  return (
    <SearchContext.Provider
      value={{
        searchResults,
        getSearchResults,
      }}
    >
      {children}
    </SearchContext.Provider>
  );
};

export default SearchProvider; ``` 
Adam
  • 375
  • 1
  • 4
  • 10

1 Answers1

2

Your state variables are being shadowed by the function parameters, not being passed in.

const getSearchResults = (searchText, pageNum, productsPerPage) =>
    setSearchResults(fetchBeers(searchText, pageNum, productsPerPage));

The above function declaration means that getSearchResults expects to be passed three values and it will refer to them as searchText, pageNum, and productsPerPage. They will take precedence over any other variables within the same scope with the same name.

What you are expecting is for those three values to actually be the variables that are defined within scope.

So instead, write your function with no parameters:

const getSearchResults = () =>
    setSearchResults(fetchBeers(searchText, pageNum, productsPerPage));

Now the function will not expect any values, but have access to the state variables.

Brian Thompson
  • 13,263
  • 4
  • 23
  • 43