Monthly Archives: September 2019

My first react HOC + Redux component in Typescript

The logic: Show a component only if the user logged in

import React from 'react';
import {connect} from "react-redux";

interface AuthenticatedUserOnlyProps {
    authenticated: boolean
}


function mapStateToProps(state: State) {    
    return {
        authenticated: state.authenticated
    };
}

export function authenticatedUserOnly<T>(WrappedComponent: React.ComponentType<T>) {
    class FinalComponent extends React.Component<AuthenticatedUserOnlyProps > {
        public render() {

            const {authenticated, ...otherProps} = this.props;
            if (authenticated) {
                return <WrappedComponent {...(otherProps as T)}/>
            } else {
                return null;
            }
        }
    };

    return connect(mapStateToProps, null)(FinalComponent);
}

To use it, just

render() {
    const someComponent = authenticatedUserOnly(SomeComponent); 

    return {
        <div>
           {someComponent }
        </div>
    }
}

Springfox for 204 response

What you need to,

  • Return ResponseEntity<Void>
  • Set the @ResponseStatus for your rest controller’s method

If you don’t do that, you will get ResponseEntity as the response class in your swagger json, and you will get both 200 and 204 as your successful response code, which is not correct because your method only returns 204, no 200.

    @RequestMapping(value = "...", method = RequestMethod.POST)
    @ApiOperation(value = "...")
    @ApiResponses(value = {
            @ApiResponse(code = 204, message = "success")
    })
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public ResponseEntity<Void> someMethod(){}

IOS Safari showing a blank page when coming back to a React Component

Problem

When you go to a react component, then go to another, and finally come back, the react component is showing blank, or half-blank.

Investigation

If you inspect the page with the mobile safari inspector , you can see the elements are there, but safari just refuse to show the data on the screen.

In my case, this seems to be related with data reloading when I come back to the component. It reloads the data in its componentDidAmount() then re-render. Safari may not perform well enough to handle this kind of re-rendering.

Fix

A workaround is to not reload the data when you come back to the component. You can do this by checking if the data exists, and only loads the data if not existing.

It comes with a price: when you come back to the component, you are not seeing the data that’s up-to-data. There are a few things you can do to make it up:

  • A delayed data re-loading
  • Always reload the data 24 hours (e.g.) after last data loading
  • Very important: destroy the data if a user logs out to make sure a different user won’t see the first user’s data