I am trying to fetch data from the backend and then render a custom component with props as the data fetched from the backend. Here's a snippet:
import { useEffect } from 'react';
import axios from 'axios';
import Card from './Card';
export default function DesignList() {
useEffect(() => {
async function populate() {
const response = await axios({
method: 'POST',
baseURL: 'http://localhost:3001',
url: '/recommend',
headers: { 'Content-Type': 'application/json' },
});
response.data.forEach(recommendation => {
document.getElementById('design-list').append(<Card
title={recommendation.title}
});
}
populate();
})
return (
<div id='design-list' />
)
}
I also tried to use React.createElement(<Card .../>), pushed it in an array and tried to render it but I got the same output as described below.
This gives an output on the screen but not as a HTML component. The output for each component is [object Object]
How do I render the components dynamically after fetching the props data from backend?
CodePudding user response:
Use state for showing recommendations, not dom append.
import { useEffect, useState } from "react";
import axios from "axios";
import Card from "./Card";
export default function DesignList() {
const [recommendations, setRecommendations] = useState([]);
useEffect(() => {
async function populate() {
const response = await axios({
method: "POST",
baseURL: "http://localhost:3001",
url: "/recommend",
headers: { "Content-Type": "application/json" },
});
setRecommendations(response.data);
}
populate();
});
return (
<div id="design-list">
{recommendations.map((item) => (
<Card title={item.title} />
))}
</div>
);
}