TILT- Angular2React–part 28

I was thinking to learn React – and transform the Angular site to React.

The steps that I took are the folllowing:

  1. Learn React from https://reactjs.org/tutorial/tutorial.html – and learning that React is a library, not a framework

  2. Learn useEffect, useState with Hooks – very easy

  3. Learn that React can have a TypeScript template – it will make harder to develop, but in the end it is safer.

Lesson Learned:

1.The typescript classes are the same – so can be translated from Angular to React

  1. The Observables are the same, with a difference: HttpClient does not exists. So we pass from HttpClient to Ajax

In Angular:

return ajax.get<string>(this.baseUrl+`PublicTILTs/CountTILTs/${id}/count`,options)

In React

this.http.get(this.baseUrl+`PublicTILTs/CountTILTs/${id}/count`,options)
  1. Environment.ts is modified to .env.local and .env.production

In Angular

export const environment = {
  production: true,
  url: 'https://tiltwebapp.azurewebsites.net/',  
};

As a usage ,

import { environment } from 'src/environments/environment';
//code
this.baseUrl=environment.url+'api/';

In React

PUBLIC_URL=/ReactTilt
REACT_APP_PRODUCTION=true
REACT_APP_URL=https://tiltwebapp.azurewebsites.net/

As a usage

this.baseUrl=process.env.REACT_APP_URL+'api/';
  1. UseEffect can give infinite loops

If you use set from hooks in useEffect, can give infinite loops. See very important below.

useEffect(()=>{
      var publicService= new PublicTiltsService();
      var x= publicService.getUrls().subscribe(data=>{
        data.forEach( it=>{
            publicService.nrTilts(it).subscribe(a=> 
            {
              console.log("obtaining ", a );            
              addTilts((prevState:publicTilt[])=>  [...prevState, a] );
            }
            );
          });
  
      });
      return ()=> x.unsubscribe();
    },[]);//very important!
  1. Do not forget about setting PUBLIC_URL .

  2. In development, if you investigate Developer Tools it is better refresh the page ( in angular it is auto refreshed)