Latest Tutorials

Learn about the latest technologies from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

How to Use State in React Components with TypeScript

When you need to store some data that won't be shared across components you can use the local component state. To use state in functional component use useState hook. This hook returns a tuple of two values. The first one is the current value of the state, the second one is a function to update the state. You can also increase type-safety declaring what types a state accepts: In class components, you can define a state as a class property called state . With TypeScript, you can declare a type for the state: The CounterProps type is used to declare what type the properties of this component support. The CounterState type will check the state types at the pre-compile time, so you will know earlier if there is an error. You don't have to annotate CounterState the second time inside of a component itself, but it allows better type inference when accessing this.state. Notice the React.Component<CounterProps, CounterState> type. This is the generic React.Component type. It takes two type-parameters that tell TypeScript how to interpret types of component props and state, so TypeScript can derive types of each field in props and the state. There is no need to mark types fields readonly since React.Component<P,S> already marks them as immutable. To change state in a class component use the setState method . This method enqueues changes in the state and causes a component to re-render.

Authentication in Angular and Parsing Cookies

Our applications are going to have authenticated users, but how do we pre-render SSR content that is protected only for users of our app? That's what I'm going to show you in this post. Remember that with Angular Universal we can parse incoming HTTP requests on our server of our Angular app and then use that data to show content, depending on who is looking at it. To do this, we inject REQUEST from @nguniversal/express-engine/tokens - and this will let us parse the request from our Angular code but on the server before we render the content. Imagine we have the following UserService on our server: Unfortunately, the request object you have in Angular is not equivalent to what you have in Express.js. There is no .cookies field to easily retrieve a cookie's names and values. We do have request headers, though, so we can extract the cookies that way. Also in the code above, we have a MongoService which lets us access a database - again, on the server, but still in our "Angular" code - as well as a decrypt function, which lets us access to cryptography functions. Cookies are sent by the browser as an HTTP header called cookie . This header contains cookie names and values delimited by the ; character: cookieName=value;cookie2=value2;andSoON=andSoOn . Let's implement the getCookie(name) method that retrieves the value of that header, splits it by the ; delimiter, and returns the value of a particular cookie specified by the function's parameter: Above, we decode the cookie string, and then store it in an object cookies . We can use that function to set up a loggedInCookie object field: Now, to create an observable representing the logged-in user's ID, you can either decrypt the ID value if it's present or return null : While it's great that we can get the userId - we probably want to use that id for something more interesting. For example, we might want to fetch the user object or check for permissions or render some special content. For now, let's fetch the whole user from the database. We'll use this userId to build an observable representing the currently logged-in user: The code above creates the currentUser$ observable by piping userId$ to the mergeMap() operator. Within mergeMap() , you retrieve the given user's data from MongoDB or return null if userId is not present (which means the user is not authenticated). Now that we have this currentUser$ observable, we can implement other helper functions for example, we can add isLoggedIn or getFavorites to our UserService : Angular Universal is incredibly powerful in that it lets us access server-side content when rendering our Angular apps. To learn more, check out: Mastering Angular Universal: Build Blazing-fast Server-Side-Rendered Angular Apps .

Thumbnail Image of Tutorial Authentication in Angular and Parsing Cookies

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More

Using Node.js in Angular and TransferState

In this post, we're going to learn how to use Node.js in your Angular app and pass data between the backend and the frontend . Angular Universal provides a tool called TransferState that will help you prevent duplicate data fetching -- it's super handy and a bit advanced. Below is a tutorial that introduces the ideas of TransferState and how to use it, but if you want a step-by-step walkthrough with complete code, then grab a copy of the course . The course is about 270+ pages over 40 lessons that teach every step to creating blazing fast Angular apps. Angular Universal is a powerful tool to address the SEO pitfall of Single Page Applications. Unfortunately, it's not a magic wand, and sometimes you need to adjust your application to make it efficient. Such a problem occurs when your application performs an HTTP call (to the back-end) during the initialization. Does it make sense to perform that call as well in the back-end as in the front-end? Let's assume we're building a task application and we have a text-file tasks.json on our server, with the following in it: We could implement a back-end endpoint that will read the file content and send it back to the requester, e.g. from our express server: And then load this file via an HTTP request. But with Universal, we can take this one step further and Of course, we don't want Angular to perform HTTP calls when running on the server when we don't have to. And so with Universal we can use Node.js APIs like fs and just read the file directly . Here's how we could create the TasksService equivalent on the server: It's okay if you do a double-take on the above: isn't this Angular code? Yes it is, but that's the sort of thing we're able to do with Universal. Let's say we want to use this TaskService in a component. Here's what it could look like: Now if we were to load this page and view the Network tab, we'd see that we're still making a call to /tasks.json - but we don't need to! It would be great to introduce a mechanism that passes such data along with the application bundle. That's what TransferState is for. To use TransferState we first create StateKey s to identify the data we want to transfer to the browser: Then we update the getTasks() method to set entry to the TransferState registry when data is read from the filesystem: From now, the TransferState registry will contain the TASKS entry. The registry will be passed along with the rendered view to the browser! Now on the browser side, we need to configure it to read from the StateKey s if they exist. To do this, we inject the TransferState service, and then update getTasks() to retrieve data from the TransferState registry or fall back to an HTTP request when the registry is empty: Now if we navigate to our app, we can verify in the Network tab of the Developer Tools : And if we hit the refresh list button and we would see that the new list is retrieved via HTTP, rather than from the TransferState . Above is a quick introduction to the ideas, but of course, there are specific things you need to do to implement it for real. We walk through those details in the course. You can grab your copy here OR as part of a newline pro membership .

Thumbnail Image of Tutorial Using Node.js in Angular and TransferState

TypeScript and React - how to prevent bugs by typing props, state, and hooks

TypeScript is fantastic to use with React because it can help us catch a lot of bugs we wouldn't catch otherwise. It helps our team have good documentation and it makes React easier to use (over the long term). But there were a lot of things I didn't understand in the beginning that I wish someone would have explained to me. In this post, I'm going to walk you through the basics of using TypeScript and React, with code. We're going to look at: The key idea is that we want to define the "shape" of our props and state with TypeScript types -- and TypeScript will ensure that everything conforms to the right "shape" in our code. Here's the interface we're going to be using for props and state throughout this post: So for getting started, thankfully, create-react-app has a typescript template that has everything setup for us! You can create a new project like this: It will create a bunch of files and the main addition is the tsconfig.js file which configures the TypeScript compiler. You'll also notice that our files end in tsx instead of jsx . Also you look at the package.json you'll see some extra typescript packages, too - but because they work out of the box, we'll ignore those for now. The main thing we're going to be doing with TypeScript and React is defining components. So it makes sense to look at the typing of those components first. As you may know, there are two ways you can define components: Let's look at both: To keep it simple, let's take the classic case of a component that shows a counter with a message. A bare-minimum TypeScript class component looks like this: So far, so good, but we're missing two key parts of React components: In React, we use props to pass down values into a component and state to manage state within a component. If you think about it closely, props and state are both objects that need to have a type . Often we might have a component that has half-a-dozen props that could be passed in and we want to make sure that these props are valid keys AND valid values. One of the great things about using TypeScript with React is that the compiler will enforce this for us. So let's define an interface for the props to this component. We want to accept a message into this component as props like this: If you think about it, what we're doing is passing this object into the component: We can define an interface in TypeScript that describes this object. We'll do it like this: But how do we tell React that the CounterProps interface is the types for our component props? We do this by using TypeScript generics on the React.Component type. You can think of generics as parameters to a type . Generics let you make "configurable" types. It's easier if we look at the code: Now let's say we try to call this component without passing a message prop like this: ... we get an error! Here's a screenshot from my VSCode: There's a lot there, but the key point is that it's saying Property 'message is missing' Okay, so we know we need to pass a message prop. Let's try passing an invalid message prop and see what happens: Above, the number 123 is invalid because we defined our message to be a string (not a number ). Here's what I get in VSCode: Again, a lot there but the key idea is that it tells me: Type 'number' is not assignable to type 'string' Pretty cool! Okay so that deals with typing props, what about state? We deal with that much the same way, first we'll define an interface for the state: Let's keep our counter in state as the variable count : Now we pass the CounterState as the second parameter to the React.Component generic: Looking at the above code, you might be wondering, how would I ever know that state was the second generic parameter? It's in the documentation (for the types). Just like how you learn the order of function parameters in, say setTimeout , you look at the docs to learn the order of parameters for generics. Typing class components is interesting, but they're also falling out of fashion. So how would we type functional components? Well, the first way is that you don't have to add any types at all . Because we are returning JSX, TypeScript can automatically conclude that the return type of our function is JSX.Element , which is good enough for React. Of course, if you want to be verbose, you can use React.FC : But what about props? Well, with a functional component, props are just arguments so we can just type the arguments: Above we type the props as CounterProps . However, a more idomatic React style would be to destructure the props into variables like this: What about functional state? When we have a functional component we use hooks to manage state. Specifically we're going to use the useState hook. Here's what our component looks like with keeping a basic counter with useState : So in this case, if I was keeping simple values we don't need to add any extra types at all. If we keep one value within useState , it's pretty easy. Buuuuut if you've worked with React long enough you're probably suspicious of my solution here. What about in the more complicated case where our state is an object , like in our class above? Say we want our state to be the same CounterState object: To type this, we use the generics on useState : Above, notice the line with useState<CounterState> - there, we're telling TypeScript that the object in useState is of type CounterState - and so it needs to enforce that "shape" on any value it controls. So there you have it, that's the absolute basics of using React with TypeScript. You can get pretty far on just the above tips. But there's still a lot more to learn like: We cover the answers to these questions and more in  Fullstack React with TypeScript . .

Thumbnail Image of Tutorial TypeScript and React - how to prevent bugs by typing props, state, and hooks

A Guide to React createContext with TypeScript

In this post, we will dive into a technique for sharing data between React components using Context . While we usually use props to pass values, that doesn't always work if we have components in different parts of our component tree. We can use Context to share these values anywhere in our app (and we can use TypeScript to type them). Below, I'm going to show you: By the way, Context is an intermediate React topic. We cover this more in depth in Fullstack React with TypeScript . This book will help both experts and React beginners develop advanced React and TypeScript skills. Check it out . React already provides us with component state to track data in components, so why do we need a different way to track data? Component state only works inside each component. and can't share that data with other components unless you e.g. pass it using props. But with larger apps, some of the data that is shared across components might include: Context creates this common dataset that all components use. Context is a way where React apps can share data between different components. Again, the key point here is that these components don't have to have a parent-child relationship. They can be in completely separate parts of your app -- as long as they access the same context, they can share data. A Context object holds any data we assign: numbers, strings, objects, functions, arrays, etc. Here's how you create a Context with React and TypeScript: React provides us the React.createContext function. It takes any data type. In the example, I'm passing it an object with a userName property and a profilePic property. Of course, we're using TypeScript so we want to type the object in context. We could do it like this: Then to use this type, we'd use a generic when we call createContext : To see React Context in action, consider this example for localizing a weather app. In this app, we want to show weather reports in 4 different languages. The user is able to change their language or locale selection at any time. We'll support English, French, Japanese, and German. In addition, weather information must be translated to Fahrenheit or Celsius depending on the locale. Here's what the app's default interface looks like with locale set to "English (US)": Here's what it looks like when the locale is changed to "Japanese (JP)": This is how we used Context to solve this problem: These are the same general steps you will take when creating and consuming a Context in your own apps. We create a LocaleContext using the React.createContext function. It looks like this : This creates the LocaleContext . The next step provides it to the app using a LocaleProvider . We do this in our main App component: Regular components in the component tree access the values stored in the LocaleContext and use them. Here's what this looks like : Q: Does this mean that you don't need to use state anymore? A: You still need state for handling data specific to a single component. Context is for global data. Q: What about hooks like useState and useEffect , do they work with Context ? A: Yes, there's nothing that prevents you from using these parts of React with Context . We have just released Fullstack React with TypeScript This guidebook will teach you the skills you need to how to use React and TypeScript confidently in your work. You can get a copy here:

Thumbnail Image of Tutorial A Guide to React createContext with TypeScript