Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useState, useReducer, useEffect } from 'react';
- import { useSNAPI } from '../context/snapi-context';
- const LOADING = Symbol('LOADING');
- const SUCCESS = Symbol('SUCCESS');
- const UNAUTHORIZED = Symbol('UNAUTHORIZED');
- const ERROR = Symbol('ERROR');
- const RecordHOC = ({ table, sysId, options, renderSuccess, renderLoading, renderError, renderUnauthorized }) => {
- const [state, dispatch] = useReducer((state, action) => {
- switch (action.type) {
- case 'success':
- return {
- stage: SUCCESS,
- component: renderSuccess,
- data: action.data,
- };
- case 'error':
- return {
- stage: ERROR,
- component: renderError,
- data: action. data,
- };
- case 'unauthorized':
- return {
- stage: UNAUTHORIZED,
- component: renderUnauthorized,
- data: null,
- };
- case 'loading':
- return {
- stage: LOADING,
- component: renderLoading,
- data: null,
- };
- default: throw new Error();
- }
- }, {
- stage: LOADING,
- component: renderLoading,
- data: null,
- });
- const sn = useSNAPI();
- const fetch = async (table, sysId, options) => {
- const response = await sn.getRecord(table, sysId, options);
- if (response.ok) {
- const data = await response.json();
- dispatch({
- type: 'success',
- data
- });
- } else if (response.status == 401) {
- dispatch({ type: 'unauthorized' });
- } else {
- try {
- const data = await response.json();
- dispatch({
- type: 'error',
- data
- });
- } catch (e) {
- console.log(response);
- dispatch({
- type: 'error',
- data: response,
- });
- }
- }
- }
- useEffect(() => {
- (async () => {
- fetch(table, sysId, options);
- })();
- }, []);
- console.log(state.component);
- return (
- <div>
- </div>
- );
- }
- export default RecordHOC;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement