0% found this document useful (0 votes)
8 views28 pages

Web Programming: Week 14

Uploaded by

hamnakhalid200
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views28 pages

Web Programming: Week 14

Uploaded by

hamnakhalid200
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

CS-311

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

CS-311 Web Programming Mohammad 2 Fall 2023


MERN STACK

CS-311 Web Programming Mohammad 3 Fall 2023


Fetching Data from APIs in React

• Fetching data from APIs (Application Programming Interfaces) is a crucial aspect of


modern web development to retrieve and display dynamic content.

CS-311 Web Programming Mohammad 4 Fall 2023


Fetching Data from APIs in React -
Cont'd

CS-311 Web Programming Mohammad 5 Fall 2023


Methods for Fetching Data
• Using fetch()
• JavaScript's native fetch() method is commonly used to make HTTP requests.
• It returns a Promise and allows you to make requests to a server and handle the response.

fetch('https://api.xyz.com/resource')
.then(response => response.json())
.then(data => {
// Handle fetched data here
})
.catch(error => {
// Handle errors here
});

CS-311 Web Programming Mohammad 6 Fall 2023


Methods for Fetching Data - Cont'd

• Using axios
• axios is a widely used HTTP client library that simplifies making requests and handling
responses.

import axios from 'axios';

axios.get('https://api.xyz.com/resource')
.then(response => {
// Handle fetched data here
})
.catch(error => {
// Handle errors here
});

CS-311 Web Programming Mohammad 7 Fall 2023


Fetching Data in React Components

• 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
}
}

CS-311 Web Programming Mohammad 8 Fall 2023


Fetching Data in React Components -
Cont'd
• Functional Components with Hooks (using useState and useEffect)
import React, { useState, useEffect } from 'react';

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

// Render component UI using fetched data


}

CS-311 Web Programming Mohammad 9 Fall 2023


Fetching Internal API

DEMO

CS-311 Web Programming Mohammad 10 Fall 2023


Cross-Origin Resource Sharing
(CORS)
CORS is a security feature implemented in web browsers that controls and manages how web pages or web
applications on one domain can request and interact with resources from another domain. It allows servers to
specify who can access their resources and which HTTP methods (GET, POST, PUT, DELETE, etc.) are
allowed when making cross-origin requests.

CS-311 Web Programming Mohammad 11 Fall 2023


Fetching External API

CS-311 Web Programming Mohammad 12 Fall 2023


Fetching External API

DEMO

Code Available at:


https://mohammad.nccsuetp.com/wp/lectures/week14/resources/Week14-Code.zip

CS-311 Web Programming Mohammad 13 Fall 2023


Context API for State Management

State management is a crucial aspect of modern web development. It involves


managing and sharing data across different components of an application. The
Context API in React provides a way to pass data through the component tree
without having to pass props manually at every level.

CS-311 Web Programming Mohammad 14 Fall 2023


What is Context API?

CS-311 Web Programming Mohammad 15 Fall 2023


Before Context API

CS-311 Web Programming Mohammad 16 Fall 2023


After Context API

CS-311 Web Programming Mohammad 17 Fall 2023


When to use Context

CS-311 Web Programming Mohammad 18 Fall 2023


When to use Context - Cont'd

CS-311 Web Programming Mohammad 19 Fall 2023


How to Use Context API

CS-311 Web Programming Mohammad 20 Fall 2023


Core Concepts in Context API
• Provider
• Role: The <Provider> component makes the data available to all components within its tree.
• Usage: Wraps the root component or a part of the component tree where the context is intended to be
available.
• Prop: Accepts a value prop to provide the data that will be accessible to consumers.
• Consumer
• Role: The <Consumer> component enables consuming the context value within the component tree.
• Usage: Utilizes a render prop pattern to access the context value provided by the nearest <Provider>
component.
• Access: Allows components to access the context value and consume it as needed.
• createContext()
• Function: A method to create a new context object.
• Default Value: Specifies the initial value that will be used when no <Provider> component is found in the
tree.
CS-311 Web Programming Mohammad 21 Fall 2023
Creating a Context
• Syntax: const MyContext = React.createContext(defaultValue);
• React.createContext() Function:
• Creates a new context object to be utilized within the React application.
• Parameter defaultValue: Specifies the initial value for the context. This value is used when no
<Provider> component is available to provide a context value.
• Example:

// Creating a context with a default value


const ThemeContext = React.createContext('light');

// Providing the context value using Provider


<ThemeContext.Provider value="dark">
{/* Components consuming the 'dark' theme */}
</ThemeContext.Provider>

CS-311 Web Programming Mohammad 22 Fall 2023


Provider Component
• Usage of <MyContext.Provider>
• Role: The <MyContext.Provider> component supplies the context value to all components nested
within its tree.
• Value Prop: Accepts a prop named value to provide the context data.
• Example:
<MyContext.Provider value={/* Your context data */}>
{/* Components consuming the context */}
</MyContext.Provider>

• Providing Values to Consumers


• Context Propagation: The value provided by the <Provider> cascades down to all <Consumer>
components within its subtree.
• Dynamic Value Updates: Changes in the context value trigger re-renders in consuming components.

CS-311 Web Programming Mohammad 23 Fall 2023


Consumer Component
• Syntax: <MyContext.Consumer>
• Consuming Context Values:
• Utilizes the <MyContext.Consumer> component to access the context data.
• Employs a render prop pattern to consume the context value.
• Example: <MyContext.Consumer>
{value => (
// Components consuming the context value
<p>Context value: {value}</p>
)}
</MyContext.Consumer>
• Accessing Context Values
• Render Prop Pattern: Involves a function as a child of the <Consumer> component to access the
context value.
• Dynamic Value Consumption: Components can respond to changes in the context value rendered by
the render prop function.

CS-311 Web Programming Mohammad 24 Fall 2023


useContext Hook
• A React hook that allows functional components to consume context without the <Consumer> component.
• Offers a more straightforward way to access context values within functional components.
• syntax: const value = useContext(MyContext);
• Example:
// Consuming context using useContext hook
const ThemeComponent = () => {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
};

• 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.

CS-311 Web Programming Mohammad 25 Fall 2023


Context API Example
// Creating a context
const ThemeContext = React.createContext('light');

// App component using the context


const App = () => { • Creation of a context using createContext().
return (
<ThemeContext.Provider value="dark"> • Shows how the <Provider> supplies the context value to
<Header />
<Content /> child components (Header and Content).
</ThemeContext.Provider>
• Utilizes the useContext hook in the Content component
);
}; to access and display the theme.
// Consuming context in Content component
const Content = () => {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
};

CS-311 Web Programming Mohammad 26 Fall 2023


Context API Example

DEMO

Code Available at:


https://mohammad.nccsuetp.com/wp/lectures/week14/resources/Week14-Code.zip

CS-311 Web Programming Mohammad 27 Fall 2023


THE END

CS-311 Web Programming 28 Fall 2023

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy