burakokumus
burakokumus

Reputation: 21

React Typescript .map is not a function error on a typed array

import React, { useState, useEffect } from "react"
import axios from 'axios'
import postImage from "assets/post_image.png"
import styled from "styled-components"

type TrendingPostsProps = {};
const TrendingPostsContainer = styled.div``;
const SinglePostContainer = styled.div``;

const TrendingPostImage = styled.img``;

const TrendingPostTitleContainer = styled.div``;

export const TrendingPosts: React.FC<TrendingPostsProps> = () => {
  interface News {
    news_id: number;
    title: string;
    datetime: string;
    summary: string;
    details: string;
    image: string;
    hit: number;
  }
  
  const [newsData, setNewsData] = useState<News[]>([]);

  useEffect(() => {

    
    const getNewsData = async () => {
      const response = await axios.get<News[]>("http://localhost:5000/news")
        setNewsData(response.data)
    }

    getNewsData()
  }, [])
  console.log(typeof newsData)
  console.log(newsData)
  return (
    <>
      <TrendingPostsContainer>
        <h2>Trending Posts</h2>
        {
        <ul>
          {newsData.map((item, index) => (
            <li key={index}>
              <SinglePostContainer>
                <TrendingPostImage src={postImage} alt=""></TrendingPostImage>
                <TrendingPostTitleContainer>
                  <h3>{item.title}</h3>
                  {/* <p>{item.date}</p> */}
                </TrendingPostTitleContainer>
              </SinglePostContainer>
            </li>
          ))}
        </ul>
        }
      </TrendingPostsContainer>
    </>
  );
};

Hi, I'm trying to fetch data from an existing backend with React Typescript. When I hover (VSCode) on the response.data in the useEffect function, it says that the data is in the type News[]. However, when I try to map it, it throws the error in the title, and if I print the newsData and its type as in the snippet, it prints this. So I thought that I should be able to iterate the data by newsData.data.map but when I do that, it says Property 'data' does not exist on type 'News[]'. I'm really confused here, the data should be an array, how can I iterate that?

Thanks in advance.

Upvotes: 0

Views: 184

Answers (2)

Viet
Viet

Reputation: 12787

you declare newsData has type Array but you setNewsData with an object. You need to update params of setNewsData is an array.

const getNewsData = async () => {
  const response = await axios.get<{data: News[]>}("http://localhost:5000/news");
  setNewsData(response.data.data);
};

Upvotes: 1

Iain McHugh
Iain McHugh

Reputation: 98

Try:

import type { AxiosResponse } from ‘axios’;

const response = await axios.get<AxiosResponse<News[]>>("http://localhost:5000/news") 
setNewsData(response.data)

Upvotes: 0

Related Questions