Cannot read properties of undefined (reading 'data')?

Здравствуйте, получаю ошибку Cannot read properties of undefined (reading 'data') при запросе данных из бд:

const getCategoryById = async () => {
        try {
            const categoryResponse = await axios.get(`${API_URL}/post-categories/${categoriesId}?populate=*`)
            const categoryData = categoryResponse.data;
            if (categoryData && categoryData.data) {
                console.log(categoryData.data);
                return categoryData.data;
            } else {
                throw new Error("Category data or category data's 'data' property is undefined");
            }
        } catch (e) {
            console.error("Error fetching post category:", e);
        }
    }

    useEffect(() => {


        if (window.sessionStorage.getItem('jwt')) {
            getUser().then(r => setUser(r))
        }
        // fetchData().then(r => r)

        getCategoryById().then(category => setPosts(category))


        if (postId) {
            setShowPostDetail(true); // Если id определен, показать детали поста
        }
    }, [])

Потом пытаюсь вывести все данные:
return (

        <ThemeProvider theme={defaultTheme}>
            {/*<Navigate to="/1/1" replace/>*/}
            <CssBaseline/>
            <Container maxWidth="xl">
                <Header user={user} title="Blog"/>
                <main>
                    <MainFeaturedPost post={mainFeaturedPost}/>
                    <Grid container spacing={6} sx={{mt: 3}}>

                        {

                            showPostDetail ? <PostDetail/> : (
                                <>
                                    {posts?.attributes.posts.data.map((data: any, index) => (
                                        !postId ? <Posts key={index} post={data}/> : null
                                    ))}
                                </>)
                        }

                        <Sidebar
                            title={sidebar.title}
                            description={sidebar.description}
                            archives={sidebar.archives}
                            social={sidebar.social}
                        />
                    </Grid>
                </main>
            </Container>
            <Footer
                title="Footer"
                description="Something here to give the footer a purpose!"
            />
        </ThemeProvider>
    )


Ещё я написал интерфейс и прописал его ва хук useState:
export interface ICategory {
    id: number,
    attributes: {
        posts: {
            data: Array<IPost>
        }

    }
}


const [posts, setPosts] = useState<ICategory>()

Вот мой ответ с сервера API:
{
    "data": {
    "id": 1,
        "attributes": {
        "title": "Business",
            "url": "buisness",
            "createdAt": "2024-04-10T12:07:37.591Z",
            "updatedAt": "2024-04-10T13:11:36.038Z",
            "publishedAt": "2024-04-10T12:07:39.822Z",
            "posts": {
            "data": [
                {
                    "id": 1,
                    "attributes": {
                        "title": "тут мой тайтл",
                        "date_post": "2024-04-10",
                        "content": "тут контент",
                        "createdAt": "2024-04-10T07:59:56.560Z",
                        "updatedAt": "2024-04-10T09:46:28.892Z",
                        "publishedAt": "2024-04-10T08:00:01.490Z"
                    }
                },
                {
                    "id": 2,
                    "attributes": {
                        "title": "тут мой тайтл",
                        "date_post": "2024-04-10",
                        "content": "тут контент",
                        "createdAt": "2024-04-10T08:07:11.502Z",
                        "updatedAt": "2024-04-10T13:23:41.218Z",
                        "publishedAt": "2024-04-10T08:07:14.136Z"
                    }
                }
            ]
        }
    }
},
    "meta": {}
}
(Api на Starpi)
Помогите разобраться с ошибкой
  • Вопрос задан
  • 61 просмотр
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы