1

I'm struggling with the following code and I don't get why I cant assign a value to searchResults :

const [searchResults, setSearchResults] = useState({});
const onSubmit = async () => {
    try {
      setIsLoading(true);
      const response = await apiCall(formData);
      console.log(response); // response is ok
      setSearchResults(response);
      console.log(searchResults); // searchResults is empty !!!
    } catch (err) {
      showNotification.error(err.message);
    } finally {
      setIsLoading(false);
    }
  };

Why searchResult is empty ?

I have checked some guides and examples :

React: Fetch Data onSubmit, not on onChange

and

https://www.codingdeft.com/posts/react-fetch-data-api/?utm_content=cmp-true

And I still don't understand why I cant assign a value to searchResults so I could render it after that.

zlobul
  • 335
  • 1
  • 5
  • 20
  • 1
    If you need access to the data right away, simply refer to `response` instead of `searchResults`. If you're calling other functions as part of the `onSubmit` callback, pass the new data as parameter instead of relying on the state. – 3limin4t0r Feb 10 '23 at 21:33
  • I'm trying to render the data once received: {searchResults.length > 0 && searchResults.map((searchResult) => ( {searchResult.customer} – zlobul Feb 10 '23 at 21:40
  • 1
    The code in your last comment should work fine, assuming you get a successful array response from `apiCall(formData)`. Move `console.log(searchResults)` out of the callback and directly into the functional component (only for development), it should log the new data once it's set. The reason why `searchResults` isn't updated immediately after the `setSearchResults()` call is because you're still using the old scope. `searchResults` will be updated the **next render**. – 3limin4t0r Feb 10 '23 at 21:51
  • @3limin4t0r Now , after you said it should work, it suddenly started working ! I really don't get it ... I will probably need an exorcist . It turns out my code above is working and ok. Regarding your first post , thanks it was useful , however I don't think I need the useEffect as I'm doing a single call. However I will mark your first reply as a solution . Thanks a lot for your time and help ! – zlobul Feb 10 '23 at 22:13
  • I found a typo when passing one of the keys , leading to an error and in combination of the empty object from the console log I assumed it is the root cause of my issues. It was not . Thanks once again for your help ! – zlobul Feb 10 '23 at 22:20

0 Answers0