Home > Net >  Cannot read properties of undefined (reading 'map') typescript error
Cannot read properties of undefined (reading 'map') typescript error

Time:11-29

I was trying to follow a tutorial on building an app with typescript and react and I keep getting this error: ,,Cannot read properties of undefined (reading 'map')". Not sure why, can someone maybe help?

Here is the code of the component:

import { useState } from 'react';
import { useTypedSelector } from '../hooks/useTypedSelector';
import { useActions } from '../hooks/useActions';

const RepositoriesList: React.FC = () => {
  const [term, setTerm] = useState('');
  const { searchRepositories } = useActions();
  const { data, error, loading } = useTypedSelector(
    (state) => state.repositories
  );

  const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    searchRepositories(term);
  };

  return (
    <div>
      <form onSubmit={onSubmit}>
        <input value={term} onChange={(e) => setTerm(e.target.value)} />
        <button>Search</button>
      </form>
      {error && <h3>{error}</h3>}
      {loading && <h3>Loading...</h3>}
      {!error && !loading && data.map((name) => <div key={name}>{name}</div>)}
    </div>
  );
};

export default RepositoriesList;

CodePudding user response:

{!error && !loading && data && data.map((name) => {name})}

Try this. I think you forgot that data could be checked in the conditional

CodePudding user response:

data should be checked if it is undefined or not. try this code

{!error && !loading && data && data.map((name) => <div key={name}>{name}</div>)}
  • Related