Skip to content

Instantly share code, notes, and snippets.

@helgatheviking
Last active September 28, 2023 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save helgatheviking/42d92f1743e6a4443ad20b929697995a to your computer and use it in GitHub Desktop.
Save helgatheviking/42d92f1743e6a4443ad20b929697995a to your computer and use it in GitHub Desktop.
Product Data Store Example
const TYPES = {
FETCH_FROM_API : "FETCH_FROM_API",
HYDRATE_PRODUCT: "HYDRATE_PRODUCT",
};
export default TYPES;
import TYPES from "./action-types";
const { FETCH_FROM_API, HYDRATE_PRODUCT } = TYPES;
// Fetch from the API.
export const fetchFromAPI = ( path ) => {
return {
type: FETCH_FROM_API,
path,
};
}
// Set the product.
export const hydrateProduct = (product) => {
return {
type: HYDRATE_PRODUCT,
product
};
}
export const STORE_KEY = 'wc/mnm/container';
import apiFetch from '@wordpress/api-fetch';
export const FETCH_FROM_API = (action) => {
return apiFetch( { path: action.path } );
}
/**
* External dependencies
*/
import { createReduxStore, register } from '@wordpress/data';
import { controls as wpControls } from '@wordpress/data-controls';
/**
* Internal dependencies
*/
import * as selectors from './selectors';
import * as actions from './actions';
import * as resolvers from './resolvers';
import * as localControls from "./controls";
import reducer from './reducer';
import { STORE_KEY as CONTAINER_STORE_KEY } from './constants';
export { CONTAINER_STORE_KEY };
export const store = createReduxStore( CONTAINER_STORE_KEY, {
reducer,
selectors,
resolvers,
controls,
actions,
} );
register( store );
import TYPES from "./action-types";
const { HYDRATE_PRODUCT } = TYPES;
const DEFAULT_STATE = { product: false };
const reducer = ( state = DEFAULT_STATE, action ) => {
switch (action.type) {
case HYDRATE_PRODUCT: {
return {
...state,
product: action.product
};
}
default:
return state;
}
};
export default reducer;
/**
* External dependencies
*/
import { getSetting } from '@woocommerce/settings';
import { fetchFromAPI, hydrateProduct } from './actions';
/**
* Fetch a product object from the Store API.
*
* @param {number} productId Id of the product to retrieve.
*/
export function* getProduct( productId ) {
if ( productId ) {
const path = `/wc/store/v1/products/${productId}`;
const product = yield fetchFromAPI( path );
return hydrateProduct( product );
}
return;
};
export const getProduct = ( state ) => {
return state.product || false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment