DEV Community

Cover image for Typescript and the Force
Dominic Barajas
Dominic Barajas

Posted on

Typescript and the Force

I have recently been tasked with a coding challenge to utilize the Stawars API to display a list of characters from the API as well as a the information provided for each character. the code was provided by the possible employer for a super rad company that I am hoping to land a junior role with. I was a little iffy at first as its a vertical I had ever anticipated working in, but after talking with there head engineer I felt like we really hit it off and how he described the way they set up their teams as well as continue to offer stipend for learning and developing was a big draw!

to the challenge though the first part was pretty simple they provided some code that made an fetch request to the API cool cool I remember doing API fetch request although its been a while since I have for the most part been building my own APIs. but wait... what's this?

 React.useEffect(() => {
    fetchJson<{ results: PersonType[] }>
("people").then((peopleResponse) =>

      setPeople(peopleResponse.results)
    );
  }, []);
Enter fullscreen mode Exit fullscreen mode

useEffect okay that I know arrow function fetchJSON ok that's some type of method wait PersonType... uhh. Well I knew it was coming as GitHub has posted its stats TypeScript is one of the most prolific languages being used to date due to its static types, and debugging prowess once set up. As well as its much easier on ramping if you are a JavaScript user. from last years 2020 GitHub state of the octoverse it was number 4

Image description

I have also noticed a trend in more and more places I have been applying that a willingness to learn TS is a bonus for lots of compnaies.

well okay I have never used TS or looked into it other then a brief overview with a friend who is prolific with it. I had some time to get the project in, but with other applications and interviews not as much as I would have liked.

so in a little under 2 days I was able to do enough research to get about 80% of the tasks required complete. the first task was to dispaly the other information for the fetched characters. with that I searched around looking at all the files provided finding in the src folder at the top level a type.ts file

export interface PersonType {
  name: string
}
Enter fullscreen mode Exit fullscreen mode

it had declaration for the PersonType a name that was a string. ok from some deduction I should be able to add more things so I updated it looking at the JSON data through a console log of what the data being provided from the API and changed the file to look like so.

export interface PersonType {
  name: string
  height: string
  mass: string
  hair_color: string
  skin_color: string
  eye_color: string
  birth_year: string
  gender: string
  homeworld: string 
  films: string
  species: string
  vehicles: string
  starships: string
}
Enter fullscreen mode Exit fullscreen mode

I figured everything was a string for now and I could update it later if need be. I made some modifications to the JSX/TSX for the person being displayed an wooh hooh all the data was being presented. hmm but the films, startships and vehicles where showing on one line. okay lets map to make a list. huh cant edit type string with map. okay research time. I spent some time figuring out why I couldnt map out each string I console logged. it is in an array but its saying its a string?!?!

after more reaserch I found out I needed to modify my types as TS is a strict language similar to Java or C++ i needed to make sure my tpes were correct.

I needed to add the empty [] to each type that was an array to let it know that these strings were an array. a simple mistake, but boom some updating to this.

export interface PersonType {
  name: string
  height: string
  mass: string
  hair_color: string
  skin_color: string
  eye_color: string
  birth_year: string
  gender: string
  homeworld: string 
  films: string[]
  species: string
  vehicles: string[]
  starships: string[]
}
Enter fullscreen mode Exit fullscreen mode

and voila I could now map each one. hurray!

next step was to add a functionality for a user to search the list by typing in the characters name. I needed to find the perfect place to build it out and to me it made sence in the People.tsx file as that was where each Person was being set in state. I utilized a filter function with useState() making my const the [query, setQuery]

function People() {
  const [people, setPeople] = React.useState<PersonType[]>([]);
  const [query, setQuery] = useState(""); 

  React.useEffect(() => {
    fetchJson<{ results: PersonType[] }>("people").then((peopleResponse) =>
      setPeople(peopleResponse.results)
    );
  }, []);

  return (
    <div>
      <div className="searchContainer">
        <input
          className="searchInput"
          placeholder="Search By Name"
          onChange={(event) => setQuery(event.target.value)}
        />
      </div>

      {people
        .filter((person) => {
          if (query === "") {
            return person;
          } else if (person.name.toLowerCase().includes(query.toLowerCase())) {
            return person;
          }
        })
        .map((person) => (
          <Person person={person} />
          ))}
    </div>
  );
}

export default People;
Enter fullscreen mode Exit fullscreen mode

I created a container and input to allow me to add CSS later. then filtering through my list of people if the search bar was empty it would return the list if it started to be typed in it would convert everything to lowercase to make it easier on both the typed information and the names on the list then on screen would update to return that matching query. No need to hit submit I wanted it to lie filter to make less work on the user and to make a cooler looking functioning search bar. I then added the map function after the filter to make sure that it still showed on the list all the People.

After that adding some CSS and <fieldset> tags and the like I made it look all shiny and nice. giving it a real Starwars vibe

starwars app

The last thing I wasn't able to do due to time. Was to get the secondary information as in films, starships, and vehicles. through the API they were linked as a URL to another resource with its own attributes as you can see in the image above.

I have a time setup to do some pair coding and hopefully we can get through that as I haven't been able to research it on my current job hunt schedule this week.

I will update with that functionality either with their help or when I have time to research later next week!

Top comments (1)

Collapse
 
johnkazer profile image
John Kazer

I like the thought process description, makes it a more useful learning experience than just explaining completed code