Basic GET request

We'll start off by getting the posts using a basic GET request with axios, and then rendering them in an unordered list:

  1. Let's open App.tsx and add an import statement for axios
import axios from "axios";
  1. Let's also create an interface for the posts that will come from JSONPlaceholder:
interface IPost {
userId: number;
id?: number;
title: string;
body: string;
}
  1. We are going to store the posts in state, so let's add an interface for this:
interface IState {
posts: IPost[];
}
class App extends React.Component<{}, IState> { ... }
  1. Let's then initialize the post-state to an empty array in a constructor:
class App extends React.Component<{}, IState> {
public constructor(props: {}) {
super(props);
this.state = {
posts: []
};
}
}
  1. When getting data from a REST API, we usually do this in the componentDidMount life cycle method. So, let's do this with axios to get our posts:
public componentDidMount() {
axios
.get<IPost[]>("https://jsonplaceholder.typicode.com/posts")
.then(response => {
this.setState({ posts: response.data });
});
}
  • We use the get function in axios to get data, which is a promised-based function like fetch
  • This is a generic function that accepts the response body type as a parameter
  • We pass the URL we are requesting as the parameter to the get function
  • We can then handle the response in the then method
  • We get access to the response body via the data property in the response object that is typed, as per the generic parameter

So, straight away this is nicer than fetch in two ways:

  • We can easily type the response
  •  There is one step (rather than two) to get the response body
  1. Now that we have the posts in the component state, let's render the posts in the render method. Let's also remove the header tag:
public render() {
return (
<div className="App">
<ul className="posts">
{this.state.posts.map(post => (
<li key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</li>
))}
</ul>
</div>
);
}

We use the posts array's map function to display the posts in an unordered list.

  1. We reference a posts CSS class, so let's add this to index.css:
.posts {
list-style: none;
margin: 0px auto;
width: 800px;
text-align: left;
}

If we look at the running app, it will now look like the following:

So, a basic GET request with axios is nice and easy. We need to use the componentDidMount life cycle method in a class component to make a REST API call that will have data from the response rendered.

How do we handle errors though? We'll cover this in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.168.56