React with Typescript


React, TypeScript

Updated Aug 26th, 2022

I like to see a component’s prop’s type/interface defined right above the comp so you know what is coming in via props. Of course if it used across multiple places you will want to define in a centralized location and import where necessary. When you put in a different file the definition is still available in a little popup on hover but only for types and not interfaces (also not for enums)? This is annoying.

Hover over a React Hook and right click -> Go to definition for more detailed information

React.FC

React.FormEvent

useRef<HTMLInputElement>(null) in combo with textInputRef.current!.value

children?: React.ReactNode

ReactElement

useState<string | null>(null)

Testing Async

From the Jack Herrington video linked below

describe("getPokemon", () => {
  it("should get a list", () => {
    getPokemonList().then(list => {
      expect(list.results[0].name).toBe("bulbasaur")
    })
  })
})

The test will fail with the “Cannot log after tests are done” error. Pass “done” keyword as parameter into “it” function and call “done()” at the end. If you define the “it” function as “async” you don’t need to worry about the “done” keyword.

Make Your Own Promise

const getFirstPokemon = async (): Promise<Pokemon> => {
  new Promise(() => {
   try{
    const list = await getPokemonList()
    resolve(await getPokemon(list.results[0].url))
   } catch (e) {
    reject(e)
     }
  })
}

Promise As a Cache

Once a promise is fulfilled any future requests are ready.

Local Storage

The following line was throwing an error:

tdCars = JSON.parse(localStorage.getItem("tdCars"))

The warning: Argument of type ‘string | null’ is not assignable to parameter of type ‘string’. Type ‘null’ is not assignable to type ‘string’.

Had to use a solution from Stack Overflow here.

Sources

There is a section in the TypeScript course by Max about React with TS. The notes are here.

TS for React Components From Beginners to Masters by Jack Herrington here.

React Hooks with Typescript by Jack Herrington video here and github here, (including useContext and useReducer).

State Management TS using only React by Jack Herrington video here.

Need to know if useReducer with TS is different than useImmerReducer.

Async code by Jack Herrington here and notes below.

Good example video here of project of quiz using styled-components from FCC, chill swedish instructor (weibenfalk). There is a separate standalone post on this.

Another video from same instructor as above building a shopping cart here. Styled comps, material-ui, react query.

Here is a TS/React cheatsheet mentioned in Herrington’s video above.

TS section in official React Docs here.

Another highly recommended resource here. I don’t use redux but I do use Jest.