0

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;
6
  • Could you confirm what kind of value newsData holds may be include a small example.
    – phuzi
    Commented Jul 27, 2021 at 12:56
  • Is your api responding with an array of data? Have you tried consoling it? newsData.map is not a function is shown when the response is not an array
    – RABI
    Commented Jul 27, 2021 at 12:56
  • are you getting array type data in res when you make axios call?
    – Amruth
    Commented Jul 27, 2021 at 12:56
  • 2
    res probably isn't an array. Use console.debug(res) to see what's in it
    – jd182
    Commented Jul 27, 2021 at 12:57
  • Does this answer your question? Axios GET request not working
    – Amruth
    Commented Jul 27, 2021 at 13:24

1 Answer 1

2

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)
1
  • @PhilippeTankoano Happy to ear that. Have a nice coding =) Commented Jul 27, 2021 at 13:02

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.