API GET from React.FC unable to pass to component

Viewed 18

I am currently trying to make a webapp with React frontend and Rails 7.0.1 backend API.

I'm trying to GET data from the rails API, but am facing trouble identifying if the problem is :

  1. incorrect GET process from axios
  2. passing of data from page "Home.tsx" to component "ArticlesList.tsx"

Here is my Home.tsx page trying to get data from the API

const API_URL = 'http://localhost:3000/api/v1/articles';

function getAPIData() {
    return axios.get(API_URL).then((response) => response.data);
}

const Home: React.FC = () => {
    ...

    const [articles, setArticles] = useState([]);
    useEffect(() => {
        getAPIData().then((items) => {
            setArticles(items);
        });
    }, []);

    return (
        <>
            ...
            <br />
            <ArticlesList articles={articles} />
        </>
    );
};

export default Home;

Here is my ArticlesList.tsx component attempting to display the data

import Data from '../TestArticles.json';
import React from 'react';
import '../App.css';

interface articles {
    id: number;
    title: string;
    body: string;
}

const ArticlesList: React.FC<{ articles: any }> = ({ articles }) => {
    return (
        <div>
            <h1>{'List of Articles from API'}</h1>
            {articles.map((article: any) => (
                <div key={article.id}>
                    <h2>{article.title}</h2>
                    <p>{article.body}</p>
                </div>
            ))}
        </div>
    );
};

export default ArticlesList;

I believe that the problem does not lie with the component as through testing with a .json file, I am able to load my entries on the page. See photo: Current page vs Expected page

I am quite new and would also appreciate any advice in improving or troubleshooting the code!

1 Answers

I was getting a access-control-allow-origin error from console. Richard Peck's solution resolved the issue.

Related