Julie
Julie

Reputation: 514

TypeError: Cannot read property 'map' of undefined - React

I am working on a search field where I want to return data to the user, and I get the error: TypeError: Cannot read property 'map' of undefined. I cant seem to find out why the map is undefined,

Here is my code: code sandbox

I tried to take sample code from j-fiddle(code below) and turn it into a functional component. Here is the code I tried to manipulate from j-fiddle

class Wrapped extends React.Component {
    constructor(props){
    super(props)
    this.state = {
        results: []
    }
    
    this.search = this.search.bind(this)
  }
  search(results){
    this.setState({results})
  }
    render(){
    const { results } = this.state
    return (
        <div>
          <Search onSearch={this.search} />
        <Result {...this.state} />
        </div>
    )
  }
}

class Search extends React.Component {
    constructor(props){
    super(props);
    this.state = {
        searchValue: ''
    }
    this.handleOnChange = this.handleOnChange.bind(this);
  }
  
  handleOnChange(e){
    this.setState({
        [e.target.name]: e.target.value
    }, () => {
        setTimeout(() => {
        // it can be the result from your API i just harcoded it
        const results = ['hello', 'world', 'from', 'SO'].filter(value => value === this.state.searchValue)
        this.props.onSearch(results)
      }, 1000)
    })  
  }
  
    render(){
    return (
        <div>
          Search: <input name="searchValue" type="text" onChange={this.handleOnChange} />
        </div>
    )
  }
}

const Result = ({results}) => {
    return (
  <ul>
    {results.map(result => <li key={result}>{result}</li>)}
  </ul>
  )
}

ReactDOM.render(
  <Wrapped/>,
  document.getElementById('container')
);

Upvotes: 0

Views: 412

Answers (1)

rigojr
rigojr

Reputation: 361

I was checking your code and found the following error into the Wrapped.js:

<Results {...results} />

Since results is declared as follow:

const [results, setResults] = useState([]);

The {...results} will spread the content array into properties in a bad way, I advice you to read about the Spread Operator here.

In order to fix your error, you can do one of the following solutions:

The Easy Solution

<Results results={results} />

The Spread Operator Solution

...
const resultsProps = {
    results,
  }
...
  return (
    <>
      <SearchComp onSearch={search} />
      <Results {...resultsProps} />
    </>
  );
...

Hope this works for you, please let me know and remember to read about the Spread Operator, it is a really useful function in .JS.

Upvotes: 2

Related Questions