Here I am trying to change products data according to category,
I have an index page and two components named Products
and Categories
. At first I am fetching all products by getServerSideProps
then I need to fetch category wise products when user selects a category.
Index Page
import Link from 'next/link';
import Layout from '../components/layouts/App';
import Products from '../components/Products';
import Categories from '../components/Categories';
class Index extends React.Component {
state={
products:this.props.products,
}
//receiving category id and trying to change state products
catProducts = async (cat_id) => {
const res = await fetch(`https://example.com/get_products?api_key=4e38d8be3269aa17280d0468b89caa4c7d39a699&category_id=${cat_id}`, { method: 'GET' })
const productsdata =await res.json()
console.log(productsdata)
// this.setState({products: productsdata})
}
render() {
return (
<div>
<Layout>
<div className="main-wrapper pt-35">
<div className="row">
<div className="col-lg-3">
<Categories categories={this.props.categories} catchange={this.catProducts}/>
</div>
<div className="col-lg-9 order-first order-lg-last">
<Products products={this.state.products} />
</div>
</div>
</div>
</Layout>
</div>
)
}
}
export async function getServerSideProps() {
const cats_req = await fetch('https://example.com/api/get_categories?api_key=4e38d8be3269aa17280d0468b89caa4c7d39a699', { method: 'POST' })
const categories = await cats_req.json();
const products_req = await fetch(`https://example.com/api/get_products?api_key=4e38d8be3269aa17280d0468b89caa4c7d39a699`, { method: 'GET' })
const products = await products_req.json();
return {
props: {
products: products,
categories: categories
}
}
}
export default Index
Here I am getting an error Unhandled Runtime Error TypeError: Failed to fetch
I am new to next js so I don't know how to do this, I will appreciate any advice/suggestion
Is the data coming while using getServerSideProps function is the one you want ??
What I can in catProducts is that the URL is not having '/api' in it, whereas in getServerSideProps there is '/api'. It can be one of the reason.
Also Please promise while using fetch.