Reputation: 51
I'm new to React and Next.js. I'm trying to pass down props to a child component from a fetch request to my backend (express server / MySQL database. The returned data is in json format and is currently being printed to my browser window. The child component is a ProductList, which contains the rendered Products.
import fetch from 'isomorphic-unfetch'
import ProductList from '../components/ProductList/ProductList';
const Index = () => (
<div>
<ProductList products={products}/>
</div>
)
Index.getInitialProps = async function () {
const res = await fetch('http://localhost:3000');
const data = await res.json();
return {products : data}
}
export default Index;
Upvotes: 1
Views: 20028
Reputation: 347
You have 2 ways to do it. One solution is for client-side (react) and the second one is for server-side (nextjs).
Client side - React
import {useState, useEffect} from 'react'
import ProductList from '../components/ProductList/ProductList';
const Index = () => {
const [products, setProducts] = useState()
// This logic is only executed when the component is mounted
useEffect({
const res = await fetch('http://localhost:3000');
const data = await res.json();
setProducts(data)
}, []);
return (
<div>
<ProductList products={products}/>
</div>
)
export default Index;
Server side - NextJS
import fetch from 'isomorphic-unfetch'
import ProductList from '../components/ProductList/ProductList';
const Index = ({products}) => (
<div>
<ProductList products={products}/>
</div>
)
Index.getInitialProps = async function () {
const res = await fetch('http://localhost:3000');
const data = await res.json();
return {products : data}
}
export default Index;
When a value is returned from getInitialProps
, it is injected as a prop into the page component, the page component then receives those values as parameters.
Upvotes: 4
Reputation: 9662
Simply use a state for the products and fill it from useEffect
. As the useEffect
should only run on the first render, we pass it an empty array of dependencies. Also, remember to handle any error from the fetch.
const Index = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
const getProducts = async () => {
const res = await fetch("http://localhost:3000");
const data = await res.json();
setProducts(data);
};
getProducts();
}, []);
return (
<div>
<ProductList products={products} />
</div>
);
};
Upvotes: 0