Một số mẫu hay dùng trong ReactJs
Tổng hợp các package sử dụng trên Client
js-cookie
axios
Sử dụng js-cookie để set và get LocalStorage
import Cookie from "js-cookie";
Cookie.set("userInfo", JSON.stringify(data));
Mẫu redux action
import * as types from "../constants/userContants";
import axios from "axios";
import Cookie from "js-cookie";
const signin = (email, password) => async (dispatch) => {
dispatch({ type: types.USER_SIGNIN_REQUEST });
try {
const { data } = await axios.post("/api/users/signin", { email, password });
dispatch({ type: types.USER_SIGNIN_SUCCESS, payload: data });
Cookie.set("userInfo", JSON.stringify(data));
} catch (error) {
dispatch({ type: types.USER_SIGNIN_FAILED, payload: error.message });
}
};
const register = (name, email, password) => async (dispatch) => {
dispatch({ type: types.USER_REGISTER_REQUEST });
try {
const { data } = await axios.post("/api/users/register", {
name,
email,
password,
});
dispatch({ type: types.USER_REGISTER_SUCCESS, payload: data });
Cookie.set("userInfo", JSON.stringify(data));
} catch (error) {
dispatch({ type: types.USER_REGISTER_FAILED, payload: error.message });
}
};
export { signin, register };
import * as types from "../constants/productConstant";
import axios from "axios";
const listProducts = () => async (dispatch) => {
try {
dispatch({ type: types.PRODUCT_LIST_REQUEST });
const { data } = await axios.get("api/products");
dispatch({ type: types.PRODUCT_LIST_SUCCESS, payload: data });
} catch (error) {
dispatch({ type: types.PRODUCT_LIST_FAILED, payload: error.message });
}
};
const detailProducts = (productId) => async (dispatch) => {
console.log(productId);
try {
dispatch({ type: types.PRODUCT_DETAIL_REQUEST });
const { data } = await axios.get(`/api/product/${productId}`);
dispatch({ type: types.PRODUCT_DETAIL_SUCCESS, payload: data });
} catch (error) {
dispatch({ type: types.PRODUCT_DETAIL_FAILED, payload: error.message });
}
};
const saveProduct = (product) => async (dispatch, getState) => {
try {
const {
userSignin: { userInfo },
} = getState();
dispatch({ type: types.PRODUCT_SAVE_REQUEST });
const { data } = axios.post("/api/products", product, {
headers: {
Authorization: "giakhanhlk " + userInfo.token,
},
});
dispatch({ type: types.PRODUCT_SAVE_SUCCESS, payload: data });
} catch (error) {
dispatch({ type: types.PRODUCT_SAVE_FAILED, payload: error.message });
}
};
export { listProducts, detailProducts, saveProduct };
Mẫu Reducer
import * as types from "../constants/productConstant";
const initialState = { products: [] };
const productListReducer = (state = initialState, action) => {
switch (action.type) {
case types.PRODUCT_LIST_REQUEST:
return { loading: true };
case types.PRODUCT_LIST_SUCCESS:
return { loading: false, products: action.payload };
case types.PRODUCT_LIST_FAILED:
return { loading: false, error: action.payload };
default:
return state;
}
};
export { productListReducer };
Mẫu Container
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const userSignin = useSelector((state) => state.userSignin);
const { loading, userInfo, error } = userSignin;
const dispatch = useDispatch();
useEffect(() => {
if (userInfo) {
props.history.push("/");
}
}, [userInfo]);
const submitHandler = (e) => {
e.preventDefault();
const { email, password } = e.target;
dispatch(signin(email.value, password.value));
};
Store dùng redux thunk
import { applyMiddleware, combineReducers, compose, createStore } from "redux";
import {
productListReducer,
productDetailsReducer,
productSaveReducer,
} from "./reducers/productReducer";
import Cookie from "js-cookie";
import thunk from "redux-thunk";
import cartReducer from "./reducers/cartReducer";
import { userSigninReducer, userRegisterReducer } from "./reducers/userReducer";
const cartItems = Cookie.getJSON("cartItems") || [];
const userInfo = Cookie.getJSON("userInfo") || null;
const initialState = { cart: { cartItems }, userSignin: { userInfo } };
const rootReducer = combineReducers({
productList: productListReducer,
productDetails: productDetailsReducer,
cart: cartReducer,
userSignin: userSigninReducer,
userRegister: userRegisterReducer,
produceSave: productSaveReducer,
});
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
rootReducer,
initialState,
composeEnhancers(applyMiddleware(thunk))
);
export default store;
Nhận xét