简体   繁体   中英

How can I prevent TypeError: Cannot read property 'map' of undefined when submitting empty form data?

Ok so my code works great but when I hit submit while the input field is empty my.map method doesnt have a input value to add to the end of the API string to search for so I get a typeError: cannot read property of map undefined. because input is my state and if I dont enter a string into the input field the state doesnt get updated so the.map method has no updated state to go off of. SO how would I set the input field to require text to be entered before the submit button will even call the function "SearchApi"?
I was trying to set conditionals but it didnt seem to work....like....if input.length < 1 { setInput("ET") just so it has something to search for and doesn't return an error. I also was looking online at react form validation tutorials but I feel like maybe i'm going about this all wrong. Any help would be appriciated thank you!

import React, {useState, useEffect} from 'react';


const SearchBar = () => {
const [search, setSearch] = useState([]);
const [input, setInput] = useState('');
const [trending, setTrending] = useState([]);
const [upcoming, setUpcoming] = useState([]);


 

// Input Field
const onUserInput = ({target}) => {
    setInput(target.value);

}

//  Api Call 
const SearchApi = (event) => {
    const aUrl = "https://api.themoviedb.org/3/search/movie?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";
   const newUrl = aUrl +'&query=' + input;
 event.preventDefault();
       
    fetch(newUrl)
    .then((response) => response.json())
    .then((data) => {
       setSearch(data.results);
        
    })
    .catch((error) => {
        console.log('Error!! Data interupted!:', error)
    })
    }

    
      return (
        //   Heading
<div>
    <div className="container">
        <h1>Movie Search Extravaganza!</h1>

        {/* Input Field and Button Form */}
      <form>
        <input value={input} onChange={onUserInput} type="text" className="searchbar" aria-label="searchbar" placeholder="search" name="movie" required/>
        <br></br>
        <button type="submit" onClick={SearchApi} aria-label="searchbutton" className="searchBtn">Movie Express Search</button>
      </form>
     </div>

    <div className="byName-container">
        <h1 className="row-label" tabIndex="0">Movies Related To Your Search</h1>
      <ul className="flexed-search">
          {search.map((item) => 
          <div className="poster-container">
          <li className="list-item"  key={item.id}>
           <img className="image-element" tabIndex="0" alt="movie poster" aria-label={item.title} src={`https://image.tmdb.org/t/p/w500${item.poster_path}`} />
          <h3 className="posterTitle">{item.title}</h3>
          </li>
          </div>
       )}
      </ul>
        </div>
 

<div className="trending-container">
    <h1 className="row-label" tabIndex="0">This Weeks Trending Tittles</h1>
    <ul className="flexed-trending">
    {trending.map((it) => 
    <div className="poster-container">
    <li className="list-item"  key={it.id}> <img className="image-element" tabIndex="0" aria-label={it.title} alt="movie poster" src={`https://image.tmdb.org/t/p/w500${it.poster_path}`} />
    <h3 className="posterTitle">{it.title}</h3>
    </li>
    </div>
    )}
    </ul>
</div>


<div className="upcoming-container"> 
<h1 className="row-label" tabIndex="0">Upcomming Movies</h1>
 <ul className="flexed-upcoming">
 {upcoming.map((inn) => 
 <div className="poster-container">
 <li className="list-item"  key={inn.id}>
 <img className="image-element" tabIndex="0" alt="movie poster" aria-label={inn.title} title={`${inn.title}: ==>  ${inn.overview}`} src={`https://image.tmdb.org/t/p/w500${inn.poster_path}`} />
 <h3 className="posterTitle">{inn.title}</h3>
 </li>
 </div>
 )}
 </ul>


</div>
        

        </div>


    )
};

export default SearchBar;```

You made a small mistake in your form

Change this:

<form>
...
<button type="submit" onClick={SearchApi} aria-label="searchbutton" className="searchBtn">
   Movie Express Search
  </button>
</form>

By:

<form onSubmit={SearchApi}>
...
<button type="submit" aria-label="searchbutton" className="searchBtn">
   Movie Express Search
  </button>
</form>

The "required" of the input will work. Demo: Stackblitz


PS: Check the keys in all your map functions

  {search.map(item => (
    <div className="poster-container">     //pass the key here and do the same for others
      <li className="list-item" key={item.id}>

you could try to make required explicit with

required={true}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM