Adding Fetch Functionality - ldco2016/microurb_web_framework GitHub Wiki
This wiki covers my implementation of save()
and fetch()
methods.
Inside of my interface UserProps
I added in the new optional property of id like so:
interface UserProps {
id?: number;
name?: string;
age?: number;
}
The id
gets tied into a user so if they have an id
that means they have a saved backend representation. If it doesn't have an id
that means the model is brand new and there is probably no backend representation for them. That id
will also customize requests made with axios
to retrieve or save some information.
Next, defining the fetch()
method:
fetch(): void {
}
Inside of fetch()
I need to make a request over to my JSON Server and I need to ensure that I attempt to make a GET request that has the id of the user tied to it like in the table you see below:
So the request is made to /users/:id
and to do so at the top of the Users.ts
file I have to import axios from 'axios';
, then inside of fetch:
fetch(): void {
axios.get(`http://localhost:3000/users/${this.get('id')}`);
}
The way we access properties on the user is by using the get()
method.
That request above returns a Promise so I have to chain on a .then()
statement like so:
fetch(): void {
axios.get(`http://localhost:3000/users/${this.get('id')}`).then((response: AxiosResponse): void => {
});
}
AxiosResponse
is an object coming from the axios
library that contains the response information I get back from that endpoint. So that AxiosResponse
type has to be also be imported from the axios
library like so: import axios, { AxiosResponse } from 'axios';
Inside of response
is the JSON data that I get back from the API and that should contain the id
and the name
and the age
of the user just fetched.
Inside of the .then()
statement I take that information and set it on the user like so:
fetch(): void {
axios.get(`http://localhost:3000/users/${this.get('id')}`).then((response: AxiosResponse): void => {
this.set(response.data);
});
}
response.data
is the actual JSON data being returned from the server and I take that object that represents the user which is this thing below:
{
"users": [
{
"name": "myname",
"age": 20,
"id": 1
}
]
}
And I am just going to set it on the user model and update all its current properties like so:
fetch(): void {
axios.get(`http://localhost:3000/users/${this.get('id')}`).then((response: AxiosResponse): void => {
this.set(response.data);
});
}