Monday

Exception handling in react with typescript

withRenderCtrl.tsx
import React from 'react';
import Loading from '../../commons/loading/loading';
import ErrorBoundary from '../../commons/error/errorBoundary';
import EmptyHint from '../../commons/empty/emptyHint';

export interface WithRenderCtrlProp {
  isDataReady: boolean;
  isLoading: boolean;
  customEmptyMessage?: string | null;
  errorMessage: string | null;
}

const withRenderCtrl = <P extends object>(Component: React.ComponentType<P>) =>
  class WithLoading extends React.Component<P & WithRenderCtrlProp> {
    render() {
      const { isDataReady, isLoading, errorMessage, customEmptyMessage, ...props } = this.props;

      if (isDataReady) return <Component {...props as P} />;
      if (errorMessage) return <ErrorBoundary errorMessage={errorMessage}/>;
      if (isLoading) return <Loading />;
      return <EmptyHint customMessage={customEmptyMessage}/>;
    }
  }

export default withRenderCtrl;
emptyHint.tsx
import React from 'react';

interface IProps {
  customMessage?: string | null;
}
 // custom message is not necessary, if it is not given then a common message will be shown
const EmptyHint = ({ customMessage = null }: IProps) => (
  <div>
    <div>{customMessage ? customMessage : 'common message for no data found '}</div>
  </div>
);

export default EmptyHint;
errorBoundary.tsx
import React from 'react';

interface IState {
  error: any;
  info: any;
}

interface IProps {
  errorMessage: any | null;
}

// also it has componentDidCatch method
class ErrorBoundary extends React.Component<IProps, IState> {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      info: null,
    };
  }

  componentDidCatch(error, info) {
    this.setState({
      error: error,
      info: info,
    });
  }

  render() {
    if (this.state.error || this.props.errorMessage) {
      return (
        <div>
          <h1>...... :( </h1>
            {this.state.error && this.state.error.toString()}
            {this.props.errorMessage && this.props.errorMessage.toString()}
        </div>
      );
    }
    return this.props.children;
  }
}

export default ErrorBoundary;
loading.tsx
import React from 'react';

const Loading = () => (
    <div>Wait for loading....</div>
);

export default Loading;
example:
import React from 'react';

// define props, states vs. ...

class Example extends React.PureComponent {

  // ...
  // when you calling your api, you should set loading, error props.
  async componentDidMount() {
    const { setMyData,  setLoader, setError } = this.props;

    setLoader(true);
    const myData = await getMyData()
      .catch((error) => {
        setError(error);
      });
    setLoader(false);

    setMyData(myData);
  }

  render(){
    const { myData, isLoading, error } = this.props;
    // usually your main component gets data, sets error & loading cases. It has callback methods vs.
    // The component named with Body includes html, css stuffs.
    // and you should define your body component as following. (with wraping our HOC named as withRenderCtrl)
    // export default withRenderCtrl(ExampleBody);
    return(
        <ExampleBody
          myData={myData}
          isLoading={isLoading}
          errorMessage={error}
          isDataReady={myData && !myData.isEmpty()}
          customEmptyMessage="my custom empty data >> this props is not necessary"
        />
    );
  }
}

export default Example;
References: https://github.com/kenneth1003/react-render-ctrl

React common api calls with axios (typescript)

Firstly, create a component called as "request.ts"
import axios from 'axios';
import I from 'immutable';

const apiURL = axios.create({
  baseURL: process.env.MY_API_URL, // example: localhost:8080/
});

const request = function (options) {

  const onSuccess = function (response) {
    const data = response.data;

    if (data.myErrorFromApiAsSuccessStatus) {
      return myStructureError(data.myErrorFromApiAsSuccessStatus);
    }
    return I.fromJS({ data });
  };

  const onError = function (error) {
    if (error.response && error.response.data && error.response.data.myErrorFromApiAsSuccessStatus) {
      return myStructureError(error.response.data.myErrorFromApiAsSuccessStatus);
    }

    console.log(`
      url: ${options.url}
      message:  ${error.message}
      stackTrace: ${error.stack}
    `);

    return Promise.reject(error.message);
  };

  function myStructureError(myErrorFromApiAsSuccessStatus) {
    const error = (`
      url: ${options.url}
      message: ${myErrorFromApiAsSuccessStatus.message}
    `);
    console.log(error);

    return Promise.reject(error);
  }

  return apiURL(options)
    .then(onSuccess)
    .catch(onError);
};

export default request;

Use request component in your api calls as following: (api.ts)
import request from '../request';

export const getMyData = async(mydata: string) => {
  return request({
    url:  '/my-data',
    method: 'POST',
    data: {
      mydata : mydata,
    },
  });
};

react - fusioncharts example with typescript (stackedcolumn2d)


import React from 'react';
import FusionCharts from 'fusioncharts';
import charts from 'fusioncharts/fusioncharts.charts';
import ReactFC from 'react-fusioncharts';

// add this line if you have licence:  FusionCharts.options['creditLabel'] = false;

charts(FusionCharts);

interface IOwnProps {
  myData: any;
}

type IProp = IOwnProps;

class StackedChart extends React.PureComponent<IProp> {
  constructor(props: IProp) {
    super(props);
    this.getToolText = this.getToolText.bind(this);
  }

  getToolText(label: string, customData: string) {
    return (
      `${label}` +
      ' | ' +
      `${customData}` +
      '<br/>' +
      '<div style="width:110px;color:red;margin-left:1px;margin-top:2px;"> ' +
        'Custom Tooltip' +
      '</div>'
    );
  }

  render() {
    // const { myData } = this.props;

    const dataSource = {
      chart: {
        theme: 'fusion',
        bgColor: '#FFFFFF',
        alternateHGridColor:'#FFFFFF',
        formatNumberScale: 1,
        numberPrefix: '$',
        numDivLines: 6,
        textOutline:0,

/*      decimalSeperator: ',',
        decimals: 0,
        forceDecimals: 0,
        yAxisValueDecimals: 0,*/

        divLineThickness: 1,
        divLineAlpha: 10,

        useRoundEdges: 0,
        usePlotGradientColor: 0,

        showSum: '1',
        showLegend: 1,
        showcanvasborder: 0,
        showPlotBorder: 0,

        baseFont:'Arial, "Helvetica Neue", Helvetica, sans-serif',
        baseFontSize: 14,
        baseFontColor: '#000000',

        labelFont:'Arial, "Helvetica Neue", Helvetica, sans-serif',
        labelFontSize: 14,
        labelFontColor: '#000000',

        valueFont:'Arial, "Helvetica Neue", Helvetica, sans-serif',
        valueFontSize: 14,
        valueFontColor: '#000000',

        outCnvBaseFont:'Arial, "Helvetica Neue", Helvetica, sans-serif',
        outCnvBaseFontSize: 14,
        outCnvBaseFontColor: '#000000',

        legendItemFont:'Arial, "Helvetica Neue", Helvetica, sans-serif',
        legendItemFontSize: 14,
        legendItemFontColor: '#000000',
        legendIconScale: 1,
        legendBorderThickness: 0,
        legendShadow: 0,

      },
      categories: [
        {
          category: [
            {
              label: 'Label1',
            },
            {
              label: 'Label2',
            },
            {
              label: 'Label3',
            },
            {
              label: 'Label4',
            },
          ],
        },
      ],
      dataset: [
        {
          seriesname: 'Serie 1',
          showValues: false,
          color: '#003f5ec',
          data: [
            {
              value: 1000,
              toolText: this.getToolText(
                '$label',
                'my custom text 1'
              ),
            },
            {
              value: 2000,
              toolText: this.getToolText(
                '$label',
                'my custom text 2'
              ),
            },
            {
              value: 50,
              toolText: this.getToolText(
                '$label',
                'my custom text 3'
              ),
            },
            {
              value: 3000,
              toolText: this.getToolText(
                '$label',
                'my custom text 4'
              ),
            },
          ],
        },
        {
          seriesname: 'Serie 2',
          showValues: false,
          color: '#ffe600',
          data: [
            {
              value: 4000,
              toolText: this.getToolText(
                '$label',
                'my custom text 5'
              ),
            },
            {
              value: 2000,
              toolText: this.getToolText(
                '$label',
                'my custom text 6'
              ),
            },
            {
              value: 800,
              toolText: this.getToolText(
                '$label',
                'my custom text 7'
              ),
            },
            {
              value: 6600,
              toolText: this.getToolText(
                '$label',
                'my custom text 8'
              ),
            },
          ],
        },
      ],
    }

    return (
      <div id="my-chart-container">
        <ReactFC
          type="stackedcolumn2d"
          width="100%"
          height="250"
          dataFormat="JSON"
          dataSource={dataSource}
        />
      </div>
    );
  }
}

export default StackedChart;




Tuesday

Get parameters from url as query params in react with typescript

 Call your react as >> localhost:3000?firstParam=123&secondParam=123&thirdParam=false

IQueryParams.tsx >>
type IQueryParams = {
  firstParam?: string;
  secondParam?: string;
  thirdParam?: boolean;
};

app.tsx>>
import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import Body from './router';

interface IProp {
}

class App extends React.PureComponent<IProp> {
  constructor(props: IProp) {
    super(props);
    this.setQueryParams = this.setQueryParams.bind(this);
  }

  componentDidMount() {
    this.setQueryParams();
  }

  setQueryParams() {
    const search = window.location.search;
    const params = new URLSearchParams(search);

    const params = {
      firstParam: params.get('firstParam'),
      secondParam: params.get('secondParam'),
      thirdParam: params.get('thirdParam'),
    };

    console.log(params);
  }

  render() {
    return (
      <Router>
        <div className="app">
          <Body />
        </div>
      </Router>
    );
  }
}

export default App;

Property context does not exist on type NodeRequire

BUG: I'm getting following error while trying to:
           ** Property context does not exist on type NodeRequire
const customIcons = importAll(require.context('./', false, /\.(png|jpe?g|svg)$/));

FIX:
npm install @types/webpack-env 

Monday

React: calling a function from a string using Typescript

Example of calling functions(in actions.ts) by giving string name dynamically with the same input parameters.

actions.ts
export function actionExampleFirst(data: any) {
  console.log('actionExampleFirst has called. parameters: ' + data);
}

export function actionExampleSecond(data: any) {
  console.log('actionExampleSecond has called. parameters: ' + data);
}

callActionsDynamically.tsx
import React from 'react';
import * as actions from './actions';

interface IProp {
}

type ActionType = typeof actions;

class CallActionsDynamically extends React.PureComponent<IProp> {
  constructor(props: IProp) {
    super(props);
    this.dynamicCall = this.dynamicCall.bind(this);
  }

  componentDidMount() {
    this.dynamicCall('actionExampleSecond', 'some parameters 2');
    this.dynamicCall('actionExampleFirst', 'some parameters 1');
  }

  dynamicCall<K extends keyof ActionType>(funcName: K, data: any) {
     actions[funcName](data);
  }

  render() {
    return(
      <></>
    );
  }
}

export default CallActionsDynamically;

You will see in the console:
actionExampleSecond has called. parameters: some parameters 2
actionExampleFirst has called. parameters: some parameters 1

Tuesday

react - fusioncharts example with typescript (linear-scale-gauge)

npm install fusioncharts --save
npm install react-fusioncharts --save



chartWithParameters.tsx
import React from 'react';
import LinearChart from './linearChart';

class ChartWithParameters extends React.PureComponent {
  render() {
    return (
      <LinearChart
        belowAverageValue={"3"}
        averageValue={"7"}
        highValue={"8"}
        existingValue={"5"}
      />
    );
  }
}

export default ChartWithParameters;

linearChart.tsx
import React from 'react';
import ReactFC from 'react-fusioncharts';
import FusionCharts from 'fusioncharts';
import Widgets from 'fusioncharts/fusioncharts.widgets';

ReactFC.fcRoot(FusionCharts, Widgets);

interface IOwnProps {
  belowAverageValue: string;
  averageValue: string;
  highValue: string;
  existingValue: string;
}

type IProp = IOwnProps;

class LinearChart extends React.PureComponent<IProp> {
  render() {
    const linearChartConfigs = {
      type : 'hlineargauge',
      width : '700',
      height : '150',
      dataFormat : 'json',
      dataSource : {
        chart: {
          caption: "Example Flow Chart",
          bgColor: '#f7fcff',
          upperLimit: this.props.highValue,
          chartTopMargin: '20',
          chartBottomMargin: '20',
          valueFontSize: '12',
          gaugeFillMix: '{light-30}',
          showValue: '1',
          majorTMNumber: '11',
          majorTMColor: '#1e5779',
          showBorder: '0',
        },
        colorRange: {
          color: [
            {
              maxValue: this.props.averageValue,
              code: '#FFC533',
              label: "averageValue",
            },
            {
              maxValue: this.props.belowAverageValue,
              code: '#F2726F',
              label: "belowAverageValue",
            },
            {
              maxValue: this.props.highValue,
              code: '#62B58F',
              label: "highValue",
            },
          ],
        },
        pointers: {
          pointer: [
            {
              value: this.props.existingValue,
              showValue: '0',
              radius: '10',
              bgColor: '#6400ff',
              BorderColor: '#6400ff',
            },
          ],
        },
        trendPoints: {
          point: [
            {
              startValue: this.props.existingValue,
              endValue: this.props.highValue,
              thickness: '1',
              markerColor: '#0075c2',
              markerBorderColor: '#666666',
              markerRadius: '5',
              alpha: '30',
              displayValue: ' ',
            },
            {
              startValue: this.props.averageValue,
              thickness: '1',
              useMarker: '1',
              markerColor: '#87dc9',
              markerBorderColor: '#fff',
              markerRadius: '5',
              displayValue: ('average' + '<br/>' + 'count:' + this.props.averageValue + '<br/>'),
            },
            {
              startValue: this.props.belowAverageValue,
              thickness: '1',
              useMarker: '1',
              markerColor: '#f5be416',
              markerBorderColor: '#fff',
              markerRadius: '5',
              displayValue: ('below average' + '<br/>' + 'count:' +this.props.belowAverageValue + '<br/>'),
            },
          ],
        },
      },
    };

    return <ReactFC {...linearChartConfigs} />;
  }
}

export default LinearChart;












references:
https://www.fusioncharts.com/react-charts
https://www.fusioncharts.com/charts/gauges/linear-scale-gauge

React >> tooltip example with typescript (material-ui)

npm install @material-ui/core --save
  
tooltipExample.tsx
**   enterDelay={100}  >> tooltip is displayed in 100ms
**   leaveDelay={200} >> tooltip hides in 200ms
**  "On mobile, the tooltip is displayed when the user longpresses the element. You can disable this feature with the disableTouchListener property." ( references: https://material-ui.com/components/tooltips/ )
import React from 'react';
import Button from '@material-ui/core/Button';
import Tooltip from '@material-ui/core/Tooltip';
import './tooltipExample.scss';
import ArrowTooltip from '../../commons/arrowTooltip/arowTooltip';

const listItems = ["tooltip 1", "tooltip 2", "tooltip 3", "tooltip 4"];

class TooltipExample extends React.PureComponent {
  render() {
    return (
      <>
        <div className="custom-margin">
          <strong>Tooltip at the left on the icon</strong>
          <Tooltip
            title={listItems.map((item:string, idx: number) => <li key={idx}>{item}</li>)}
            placement="right"
            enterDelay={100}
            leaveDelay={200}
          >
            <span className="info" />
          </Tooltip>
        </div>

        <div className="custom-margin">
          <strong>ArrowTooltip at the left on the icon</strong>
          <ArrowTooltip
            title={listItems.map((item:string, idx: number) => <li key={idx}>{item}</li>)}
            placement="right"
            enterDelay={100}
            leaveDelay={200}
          >
            <span className="info" />
          </ArrowTooltip>
        </div>

        <div className="custom-margin">
          <Tooltip
            title="Tooltip at the bottom on the button"
            placement="bottom-start"
            enterDelay={100}
            leaveDelay={200}
          >
            <Button>Button example</Button>
          </Tooltip>
        </div>

      </>
    );
  }
}

export default TooltipExample;

tooltipExample.scss
(you should also add a file named as info.svg in the project)
.info {
  display: inline-block;
  background: url(./info.svg) no-repeat;
  background-size: 13px 18px;
  width: 15px;
  height: 20px;
  margin-left: 3px;
}

.custom-margin {
  margin-bottom: 25px;
}

arrowTooltip.tsx ( references: https://material-ui.com/components/tooltips/ )
import React from 'react';
import { Theme, makeStyles, createStyles } from '@material-ui/core/styles';
import Tooltip, { TooltipProps } from '@material-ui/core/Tooltip';
import PropTypes from 'prop-types';

function arrowGenerator(color: string) {
  return {
    '&[x-placement*="bottom"] $arrow': {
      top: 0,
      left: 0,
      marginTop: '-0.95em',
      width: '3em',
      height: '1em',
      '&::before': {
        borderWidth: '0 1em 1em 1em',
        borderColor: `transparent transparent ${color} transparent`,
      },
    },
    '&[x-placement*="top"] $arrow': {
      bottom: 0,
      left: 0,
      marginBottom: '-0.95em',
      width: '3em',
      height: '1em',
      '&::before': {
        borderWidth: '1em 1em 0 1em',
        borderColor: `${color} transparent transparent transparent`,
      },
    },
    '&[x-placement*="right"] $arrow': {
      left: 0,
      marginLeft: '-0.95em',
      height: '3em',
      width: '1em',
      '&::before': {
        borderWidth: '1em 1em 1em 0',
        borderColor: `transparent ${color} transparent transparent`,
      },
    },
    '&[x-placement*="left"] $arrow': {
      right: 0,
      marginRight: '-0.95em',
      height: '3em',
      width: '1em',
      '&::before': {
        borderWidth: '1em 0 1em 1em',
        borderColor: `transparent transparent transparent ${color}`,
      },
    },
  };
}

const useStylesArrow = makeStyles((theme: Theme) =>
  createStyles({
    tooltip: {
      position: 'relative',
    },
    arrow: {
      position: 'absolute',
      fontSize: 6,
      width: '3em',
      height: '3em',
      '&::before': {
        content: '""',
        margin: 'auto',
        display: 'block',
        width: 0,
        height: 0,
        borderStyle: 'solid',
      },
    },
    popper: arrowGenerator(theme.palette.grey[700]),
  }),
);

export default function ArrowTooltip(props: TooltipProps) {
  const { arrow, ...classes } = useStylesArrow();
  const [arrowRef, setArrowRef] = React.useState<HTMLSpanElement | null>(null);

  return (
    <Tooltip
      classes={classes}
      PopperProps={{
        popperOptions: {
          modifiers: {
            arrow: {
              enabled: Boolean(arrowRef),
              element: arrowRef,
            },
          },
        },
      }}
      {...props}
      title={
        <React.Fragment>
          {props.title}
          <span className={arrow} ref={setArrowRef} />
        </React.Fragment>
      }
    />
  );
}

ArrowTooltip.propTypes = {
  title: PropTypes.node,
};

screenshots:


 


Wednesday

REST API Naming Conventions

1. Do not use slash(/) at the last character of the URI
http://localhost:8080/user-authorization/users/   /* Don't */
http://localhost:8080/user-authorization/users   /* Do */

2. Use hypens (-), use lowercase letters, do not use underscore (_), do not use file extension
http://localhost:8080/userAuthorization/homeButtons          /* Don't */
http://localhost:8080/user_authorization/home_buttons        /* Don't */
http://localhost:8080/USER-AUTHORIZATION/HOME_BUTTONS        /* Don't */
http://localhost:8080/user-authorization/home-buttons.xml    /* Don't. if you want to show media type, use Content-Type header */

http://localhost:8080/user-authorization/home-buttons        /* Do */

3.If you have a hierarchical relation (like user's buttons, user's sidebar buttons) then divide this relation by using slash.
http://localhost:8080/users-buttons                /* Don't */
http://localhost:8080/users-sidebar-buttons/{id}   /* Don't */

http://localhost:8080/users/{id}/buttons            /* Do */
http://localhost:8080/users/{id}/sidebar-buttons    /* Do */     

4. Example for returning collection or a singular object:
http://localhost:8080/user-authorization/cards         /* Use this if you will return a collection of card */
http://localhost:8080/user-authorization/cards/{id}    /* Use this if only the given card will return  */

5. Do not use crud function names like get, delete, update, create.
HTTP request methods (GET, PUT, POST, DELETE) should indicate the type of the function.
/* Get given user's cards */
HTTP GET http://localhost:8080/users/{id}/cards   

/* Get given user's card for given id */
HTTP GET http://localhost:8080/users/{id}/cards/{id}  

/* create card for given user */
HTTP POST http://localhost:8080/users/{id}/cards

/* Update card for given user */
HTTP PUT http://localhost:8080/users/{id}/cards/{id}  

/* Delete card for given user */
HTTP DELETE http://localhost:8080/users/{id}/cards/{id}  

6. If you need parameters like sorting, filtering, limiting then use query parameters.
http://localhost:8080/users?sort=registration-date

Intellij: 'string template are not supported by current javascript version' error

Intellij gives following error on my react project:
  • string template are not supported by current javascript version
 FIX: 
Go to File >> Settings >> Languages & Frameworks >> Javascript
Change "Javascript language version" to "React JSX" then click to OK and wait for indexing.