Trying to update parent component from child fails on form submit

Tell us what’s happening:
Describe your issue in detail here.
Hi, all. I’m trying to update the retrieved prop from the Search component onSubmit so I’m passing a function down as props from the parent component App. When I try to log the retrieved variable on App using the getSearch() function, it comes out as null. I know that setRetrieved is asynchronous, but I tried using other methods to solve this like useEffect and even useRef(). Nothing worked. Help please? Full code is: thirsty-wind-dolu7 - CodeSandbox
Your code so far



// Change code below this line
export default function App() {
  const [retrieved, setRetrieved] = useState(null);

  const getSearch = (search) => {
    setRetrieved(search);

    console.log(retrieved);
  };

  return (
    <div className="App">
      <Search retrieved={retrieved} getSearch={getSearch} />
      {location && <Layout location={location} />}
    </div>
  );
}

import { useState } from "react";

const Search = ({ onSubmit, getSearch }) => {
  const [search, setSearch] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();

    getSearch(search);
  };

  return (
    <div className="search-container">
      {}
      <form onSubmit={handleSubmit}>
        <input
          onChange={(e) => setSearch(e.target.value)}
          type="search"
          placeholder="Enter a location, please"
          value={search}
        />
        <button className="searchLocation"> Search </button>
      </form>
      <div></div>
    </div>
  );
};

export default Search;


};
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36

Challenge: Getting Started with React Redux

Link to the challenge:

That console.log shows undefined because your setter is not immediate. Not because of anything you’ve done, just useState is an asynchronous function.

In order to log the updated value, you’d need to use a useEffect with [retrieved] as its dependency array. Doing that, the useEffect would run after the setRetrieved has run, showing the updated value.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.