Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading