componenetDidMount() lifecycle event - KatyaHorton/Udacity-React-practice GitHub Wiki
componentDidMount()
To make AJAX request - use componenetDidMount() lifecycle event.
Walkthrough:
- Compinent added to the view =>
componentDidMount()
invokes (automatically) =>componentDidMount()
initiates AJAX request- Request is finished =>
- We have response for the request =>
setState()
called =>setState()
updated the component with newly requested data
React docs says:
componentDidMount()
is invoked immediately after a component is mounted. Initialisation that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.
Add contacts from server with API request:
APIRequest => Fetch contacts from server => add contacts to our state
1.
contacts
array instead of having data should be an empty array
state: {
contacts: []
}
2.
In ContactsAPI.js (file, generated for us) exports functions, including getAll()
function, which makes request to our API and gets the contacts info, to stick inside our state.
In App.js:
import * as ContactsAPI from './utils/ContactsAPI'
3.
Add a lifecycle event to our component in which we should make an API request :
//this function is going to invoked by react whenever that component is mounted to the view
componentDidMount(){
//calling ContactsAPI.getAll() will return us a promise
ContactsAPI.getAll().then((contacts) => {
this.setState({contacts: contacts})
})}
Remove contacts also from server with API request:
1.
In our remove function we are updating out local state, but we also should make the request to an API:
removeContact = (contact) => {
this.setState((state) => ({
contacts: state.contacts.filter((c) => c.id !== contact.id)
}))
// API request
ContactsAPI.remove(contact)
}