I have a problem with my NextJS App. I want to create a Portfolio on my website, using Strapi to add some content when I realize new projects. I can’t succeed to extract the data array from Axios tu use it in my App. It is blocked in my GetProjects function.
This is the Page.jsx
import styles from './page.module.css'
import Introduce from './components/Introduce'
import Process from './components/Process'
import Scaling from './components/Scaling'
import Techs from './components/Techs'
import Portfolio from './components/Portfolio'
import Socials from './components/Socials'
import variables from './globals.scss'
import "../../node_modules/bootstrap/scss/bootstrap.scss"
export default function Home() {
return (
<main className='container-fluid'>
<Introduce />
<Process />
<Scaling />
<Techs />
<Portfolio />
<Socials />
</main>
)
}
The portfolio component :
import React from "react";
import GetProjects from "./GetProjects.jsx";
function Portfolio() {
return (
<div className='vh-100 d-flex align-items-center slide bg-waterblue row justify-content-center'>
<div className='col-md-5'>
<h2 className="text-lg-start text-center fw-bold title text-gold">My Portfolio.</h2>
<p className="text-light text-lg-start text-center fw-semibold">Some images illustrate better
than long speaches.
</p>
</div>
<div className="col-md-5">
<div className="row row-cols-4">
<div className="row">
<GetProjects />
</div>
</div>
</div>
</div>
)
}
export default Portfolio;
And this is the GetProjects.jsx component, including the function that doesn’t work:
import React from "react";
import axios from "axios";
function GetProjects() {
async function getData() {
try {
const response = await axios.get('http://localhost:1337/api/projects?populate=*');
const data = response.data.data;
// console.log(data);
return (
<div>
{function renderData(data) {
data.map(project => {
<li>{project.attributes.title}</li>
})
<div>
<ul>
{renderData(data)/* Doesn't works */}
</ul>
</div>
}}
</div>
)
} catch (error) {
console.error(error); // Don't forget to add "?populate=*" to the API endpoint.
}
}
getData()
}
export default GetProjects;
Do you have advice? Some idea to extract that array and use it in the app?
Thank you so much!
2
Answers
From the look of things you need to move the async function to get data into a React.useEffect hook and pass the result back into some react state. Then use that state to render the list.
You can read more about this in the docs: https://react.dev/reference/react/useEffect#fetching-data-with-effects
You need a
return
inGetProjects
to have something displayed on the page. As you did, it will returnundifined
. Also, you could simplify your code to: