Home > Enterprise >  How can I display the results of map function in jsx?
How can I display the results of map function in jsx?

Time:07-21

I'm slowly learning react and trying to display the results of my searchMap function (movie title/poster) with the TMDB API. I can log the information I need to the console, but I get undefined variables and other errors when trying to display the information in the commented div. https://codesandbox.io/s/ddmdu4

function App() {
  const search = async (event) => {
    const searchQuery = event.target.value;
    if (searchQuery) {
      const searchReq = await fetch(
        `https://api.themoviedb.org/3/search/movie?api_key=${process.env.API_KEY}&query=${searchQuery}`
      ).then((res) => res.json());
      const searchResults = searchReq.results;
      searchMap(searchResults);
    }
  };

  const searchMap = (searchResults) => {
    searchResults.map((movie) => {
      console.log(`${movie.title}`);
      console.log(`${movie.backdrop_path}`);
    });
  };

  return (
    <div className="App">
      <div>
        <input type="text" onChange={search} placeholder="Search"></input>
      </div>

      <div>{/* Display movie title/poster*/}</div>
    </div>
  );
}

export default App;

CodePudding user response:

Since you want to update the DOM each time the result changes I would recommend using that inside of a state like so:

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

In your async search function update the state by using its appropiate "setter":

      .then((res) => res.json());
      setSearchResults(searchReq.results);

And inside your return you can map the result as follows:

      <div>
        {searchResults.map((movie) => (
          <>
            <div>{movie.title}</div>
            <div>{movie.backdrop_path}</div>
          </>
        ))}
      </div>
  • Related