Philippe Tankoano
Philippe Tankoano

Reputation: 91

how to fix the error (is not a function) in react

hello I am learning react and currently I stumble on an error message: (TypeError: newsData.map is not a function) in my browser when I run my code. Vs code does not notify me of an error only my browser displays it (I use crome)

import React, { useEffect, useState } from "react";
import Navigation from "../components/Navigation";
import Logo from "../components/Logo";
import axios from "axios";
import Article from "../components/Article";

const News = () => {
  const [newsData, setNewsData] = useState([]);

  useEffect(() => {
    getNews();
  }, []);
  const getNews = () => {
    axios
      .get("http://localhost:3001/articles")
      .then((res) => setNewsData(res));
  };
  return (
    <div className="news-container">
      <Navigation />
      <Logo />
      <h1>News</h1>

      <form>
        <input type="text" placeholder="Nom" />
        <textarea placeholder="Message"></textarea>
        <input type="submit" value="Envoyer" />
      </form>
      <ul>
        {newsData.map((article) => (
          <Article />
        ))}
      </ul>
    </div>
  );
};

export default News;

Upvotes: 0

Views: 2835

Answers (1)

Giovanni Esposito
Giovanni Esposito

Reputation: 11156

This means that newsData is not an array. Considering that you initialized it as an empty array (const [newsData, setNewsData] = useState([]);) I think that your problem is here:

setNewsData(res)

res is not an array.

To solve this you should set newsData as:

setNewsData(res.data)

Upvotes: 2

Related Questions