We have create store website demo using react redux, react-router-dom, axios, bootstrap and fakestore api.
First of all we need to install all npm packages for create this demo. Simply copy below code in vscode terminal.
npm install react-redux redux react-router-dom react-bootstrap axios
Fake Store API - https://fakestoreapi.com/docs
Now we have to create redux folder structure for store all product data, For that we have create action-type , action, reducer and store files.
Now we have create Productlist component.
import React,{useEffect} from 'react'
import {Card,Button,Container, Row} from 'react-bootstrap';
import { useDispatch , useSelector} from 'react-redux';
import axios from 'axios';
import { setproduct } from './../redux/action/product-action';
import {Link} from 'react-router-dom';
export default function Productlist() {
const dispatch = useDispatch();
const products = useSelector(state => state.allproducts.product);
const fetchapi = async () =>{
const responce = await axios.get("https://fakestoreapi.com/products")
.catch((error)=>{
console.log(error);
})
// console.log(responce.data);
dispatch(setproduct(responce.data));
}
useEffect(() => {
fetchapi();
// console.log(products[0]);
}, []);
const rederlist = products.map((product)=>{
const {id,title,price,image,description} = product
return(
<Card style={{ width: '18rem' }} key={id}>
<Link to={`/product/${id}`}>
<Card.Img variant="top" src={image} />
<Card.Body>
<Card.Title>{title}</Card.Title>
<Card.Text>
{title}
</Card.Text>
<Button variant="primary">View Product</Button>
</Card.Body>
</Link>
</Card>
)
})
return (
<>
<Container>
<Row>
{rederlist}
</Row>
</Container>
</>
)
}
In this file we have use useEffect hook to display product list when component load. Once responce get from api we need to dispatch that data in redux action and after that it go to reducer.All the reducer using redux combineReducers component store all state data in store.js file.
0 Comments
Post a Comment