Home > database >  Error: Cannot read properties of undefined (reading 'map')
Error: Cannot read properties of undefined (reading 'map')

Time:12-24

I'm trying to build an App in React using API and when I try to show news on search input, it gives me an error: Cannot read properties of undefined (reading 'map').

function Searched() {
  const [searchedNews, setSearchedNews] = useState([]);
  let params = useParams();

  const getSearched = async (name) => {
    const data = await fetch(
      `https://newsapi.org/v2/top-headlines?apiKey=${process.env.REACT_APP_API_KEY}&q=${name}`
    );
    const news = await data.json();
    setSearchedNews(news.searched);
  };

  useEffect(() => {
    getSearched(params.search);
  }, [params.search]);

  return (
    <Grid>
      {searchedNews.map((item) => {
        return (
          <Card>
            <img src={item.urlToImage} alt={item.title} />
            <h4>{item.title}</h4>
          </Card>
        );
      })}
    </Grid>
  );
}

When I try to console.log news and search for news, it shows me an array with articles, but when I console.log(searchedNews) it shows me an empty array.

Thank you for your time!

CodePudding user response:

top-headlines endpoint returns object like this:

{
  "status": "ok",
  "totalResults": 68,
  "articles": [
    /* articles here */
  ]
}

There is no searched property

Your code should look like this:

const getSearched = async (name) => {
  const data = await fetch(
    `https://newsapi.org/v2/top-headlines?apiKey=${process.env.REACT_APP_API_KEY}&q=${name}`
  );
  const news = await data.json();
  setSearchedNews(news.articles);
};

CodePudding user response:

(if you are getting data from api)

The state will not be set in the first few renders.And it will take time for the state variable to have value.

So to escape the error you can write like searchedNews?.map((item) just add a question mark infront of searchedNews and it will run fine. The question mark makes it so that the map function only works if searchedNews has some value to it.

When your component first renders searchedNews is an empty array and the map function runs on it giving you an error.

For console.log, your console.log will show an empty array only on first few renders as the state hasn't been set, but if you use a useEffect with the dependency of searchedNews it will re-render the component whenever the value of searchedNews is changed.

Hopefully this helps.

  • Related