Let's answer the following questions to help our knowledge of what we have just learned stick:
- What will the output be in the console if we ran the following code in a browser?
try {
setInterval(() => {
throw new Error("Oops");
}, 1000);
} catch (ex) {
console.log("Sorry, there is a problem", ex);
}
- Assuming that post 9999 doesn't exist, what would be the output in the console if we ran the following code in a browser?
fetch("https://jsonplaceholder.typicode.com/posts/9999")
.then(response => {
console.log("HTTP status code", response.status);
return response.json();
})
.then(data => console.log("Response body", data))
.catch (error => console.log("Error", error));
- If we did a similar exercise with axios, what would be the output in the console when running the following code?
axios
.get("https://jsonplaceholder.typicode.com/posts/9999")
.then(response => {
console.log("HTTP status code", response.status);
})
.catch(error => {
console.log("Error", error.response.status);
});
- What is the benefit of using the native fetch over axios?
- How can we add a bearer token to the following axios request?
axios.get("https://jsonplaceholder.typicode.com/posts/1")
- We are using the following axios PUT request to update a post title?
axios.put("https://jsonplaceholder.typicode.com/posts/1", {
title: "corrected title",
body: "some stuff"
});
- The body hasn't changed though—it's just the title we want to update. How can we change this to a PATCH request to make this REST call more efficient?
- We have implemented a function component to display a post. It uses the following code to get the post from a REST API?
React.useEffect(() => {
axios
.get(`https://jsonplaceholder.typicode.com/posts/${id}`)
.then(...)
.catch(...);
});
What is wrong with the preceding code?