- Create folder - Amazona/backend
Run npm init in the root folder(amazona)
npm install express (root folder)
error: code written in ES6 , node only understands es5 --- convert it
ES6 Conversion
npm install @babel/cli @babel/core @babel/node @babel/preset-env nodemon
npm install @babel/cli @babel/core @babel/node @babel/preset-env nodemon --save-dev
Create .babelrc file in the root with below code
{
"presets": [
[
"@babel/preset-env"
]
]
}
edit package.json
"scripts": {
"start": "nodemon --watch backend --exec babel-node backend/server.js"
},
RUN backend using :
npm start
we can get the json data printed
Use react hooks to get data from the server
package.json - add the proxy code
"name": "frontend",
"proxy": "http://127.0.0.1:5000", // add this line
"version": "0.1.0",
Go to frontent - install axios
npm install axios
const [products, setProduct] = useState([]);
useEffect(() => {
const fetchData = async () =>{
const {data} = await axios.get("/api/products");
setProduct(data);
}
fetchData();
return () => {
//
};
}, [])
trouble shoot network requests
Developer Tools --- Network ---- XHR
State Management using REDUX
Go to /frontent/
npm install redux react-redux
create store with product reducers
Wrap the <App /> in index js with
const store = createStore(reducer, initialState, compose(applyMiddleware(thunk)));
//thunk is a redux middleware allows to run async operation in the action in redux
npm install redux-thunk
Add redux tool to dev tools
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSTION_COMPOSE__ || compose;
- define constants -- create constants folder
---- useSelector
create : actions ---> productActions.js
redux state , move axios code
return loading ? <div> Loading...</div>:
error ? <div>{error}</div>:
<ul className="products">
Redux to Product Details Page
Create web api --- for individual product details
create constansts
create reducers
add to store
Add to Cart & Qty
const [qty, setQty] = useState(1);
<li>
Qty: <select value={qty} onChange={(e) => { setQty(e.target.value)} } >
{[...Array(product.countInStock).keys()].map(x=>
<option key={x+1} value={x+1}>{x+1}</option>
)}
</select>
</li>