Web Programming: Week 14
Web Programming: Week 14
WEB PROGRAMMING
Week 14
Lecture 14
MOHAMMAD
Lecturer, CSIT
Lecture Outline
• Fetching Data From APIs in React • Provider Conponent
• Methods for Fetching Data • Consumer Component
• Fetching Data in React Components • useContext Hook
• Fetching Internal API • Context API Example
• Cross-Origin Resource Sharing (CORS)
• Fetching External API
• Fetching External API
• Context API for State Management
• What is Context API?
• Before & After Context API
• When to use Context API
• How to use Context API
• Core Concepts in Context API
• Creating a Context API
fetch('https://api.xyz.com/resource')
.then(response => response.json())
.then(data => {
// Handle fetched data here
})
.catch(error => {
// Handle errors here
});
• Using axios
• axios is a widely used HTTP client library that simplifies making requests and handling
responses.
axios.get('https://api.xyz.com/resource')
.then(response => {
// Handle fetched data here
})
.catch(error => {
// Handle errors here
});
• Class Components
• Use lifecycle methods like componentDidMount() to initiate API calls when the component
mounts.
class MyComponent extends React.Component {
componentDidMount() {
fetch('https://api.xyz.com/resource')
.then(response => response.json())
.then(data => {
// Update component state with fetched data
this.setState({ data });
})
.catch(error => {
// Handle errors here
});
}
render() {
// Render component UI using fetched data
}
}
function MyComponent() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.xyz.com/resource')
.then(response => response.json())
.then(data => {
// Update state with fetched data
setData(data);
})
.catch(error => {
// Handle errors here
});
}, []); // Empty dependency array triggers the effect only once
DEMO
DEMO
• Benefits of useContext
• Concise Code: Reduces code complexity by eliminating the need for render prop patterns.
• Improved Readability: Enhances code readability by directly accessing context values within functional
components.
DEMO