Now it's Axios
turn!
What is the Axios
? check the link below!
Let's do some real work.
axios
on the top of the Home.js
file.componentDidMount()
method to run some function(here is axios
) with launch.axios.get()
for mok database files and use .then()
for running after .get()
method..then
takes response from the database get by .get()
method, as an argument named res
in the render()
method.import React, { Component } from "react";
import axios from "axios";
export default class Home extends Component {
componentDidMount() {
axios.get("https://jsonplaceholder.typicode.com/posts").then((res) => {
console.log(res); // res.data has 100 of items
});
});
}
render() {
//...
}
}
state.post
array.this.setState({})
method to update state.posts
array.{posts}
variable equal to newly updated state, this.state
.boolean
variable postList
for using post.length
to check there is posts.import React, { Component } from "react";
import axios from "axios";
export default class Home extends Component {
state = {
posts: [],
};
componentDidMount() {
axios.get("https://jsonplaceholder.typicode.com/posts").then((res) => {
this.setState({
posts: res.data.slice(0, 10),
//this is only assigned 10 items in res.data
});
});
}
render() {
const { posts } = this.state;
const postList = posts.length ? (
//...
) : (
//...
);
return (
//...
);
}
}
<div className="center">No posts yet</div>
!!post.map()
function to select&return each item
.className
is Materialize Style
class
convention!{postList}
's return
! import React, { Component } from "react";
import axios from "axios";
export default class Home extends Component {
state = {
posts: [],
};
componentDidMount() {
axios.get("https://jsonplaceholder.typicode.com/posts").then((res) => {
// console.log(res);
this.setState({
posts: res.data.slice(0, 10),
});
});
}
render() {
const { posts } = this.state;
const postList = posts.length ? (
posts.map((post) => {
return (
<div className="post card" key={post.id}>
<div className="card-content">
<span className="card-title">{post.title}</span>
<p>{post.body}</p>
</div>
</div>
);
})
) : (
<div className="center">No posts yet</div>
);
return (
<div className="container">
<h4 className="center">Home</h4>
{postList}
</div>
);
}
}