0% found this document useful (0 votes)
2 views9 pages

FSD Module 4 Answer

In React, state is mutable and owned by the component, while props are immutable and passed down from parent components. Event handling in React is done through functions assigned to element properties, allowing components to update state based on user interactions. GraphQL provides a more flexible and efficient way to query data compared to REST APIs, allowing clients to specify exactly what data they need and supporting a single endpoint for all queries.

Uploaded by

sarbjotsingh1804
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)
2 views9 pages

FSD Module 4 Answer

In React, state is mutable and owned by the component, while props are immutable and passed down from parent components. Event handling in React is done through functions assigned to element properties, allowing components to update state based on user interactions. GraphQL provides a more flexible and efficient way to query data compared to REST APIs, allowing clients to specify exactly what data they need and supporting a single endpoint for all queries.

Uploaded by

sarbjotsingh1804
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/ 9

Ques: What is the difference between state and Props in React?

Provide an example.

Ans: In React, both state and props hold model information, but they differ
in key aspects. Here's a breakdown of their differences, as outlined in the
provided content:

* **Mutability**: State can be changed using `this.setState()`, while props


are immutable.
* **Ownership**: State belongs to the component itself. Props, on the
other hand, belong to an ancestor component, and the component
receives a read-only copy.
* **Information**: Both state and props hold model information.
* **Affects**: Both state and props affect the rendering of the component.

**Example:**

Consider a component displaying a list of issues, like the `IssueTable`


component mentioned in the text.

* **State**: The array of issues being displayed would be an ideal state


variable because it affects the rendered view and can change when issues
are added, edited, or deleted. The state is initialized in the `IssueList`
component and can be modified there.
* **Props**: Each individual issue in the array could be passed down to
an `IssueRow` component as a prop. The `IssueRow` component receives
this data as a read-only copy and uses it to render the details of that
specific issue. The `IssueTable` receives the issues array as props from
`IssueList`.

In essence, state is for managing data that changes within a component,


while props are for receiving data from parent components. Changes in
state can then be passed down as props to child components, triggering
re-renders as needed.

Ques: How do you handle an event in React? Provide an example


where a button click updates the component’s state.

AI: In React, event handling is achieved by supplying functions to specific


element properties like `onClick` and `onSubmit`. These properties accept
functions as values, similar to standard HTML and JavaScript event
handling.
**Example:**

The provided text details how to add an issue interactively using a button
click. Here's how the state is updated on a button click in the `IssueAdd`
component:

1. **Create a Form**: A form with text inputs for "Owner" and "Title" and
an "Add" button is created in the `render()` method of the `IssueAdd`
component.

```html
<form name="issueAdd" onSubmit={this.handleSubmit}>
<input type="text" name="owner" placeholder="Owner" />
<input type="text" name="title" placeholder="Title" />
<button>Add</button>
</form>
```

2. **Handle the Submit Event**: The `onSubmit` property of the form is


set to a class method called `handleSubmit`.

3. **Implement `handleSubmit()`**: This method receives the submit


event as an argument.
* It calls `e.preventDefault()` to prevent the default form submission
behavior.
* It retrieves the values from the input fields using
`document.forms.issueAdd`.
* It creates a new issue object with the retrieved values.
* It calls `this.props.createIssue(issue)` to pass the new issue to a
function that updates the state (likely in a parent component).
* It clears the input fields to prepare for the next input.

```javascript
handleSubmit(e) {
e.preventDefault();
const form = document.forms.issueAdd;
const issue = {
owner: form.owner.value, title: form.title.value, status: 'New',
}
this.props.createIssue(issue);
form.owner.value = ""; form.title.value = "";
}
```
In this example, clicking the "Add" button triggers the `handleSubmit`
function, which prevents the default form submission, gathers the input
values, and calls `createIssue` (passed as a prop) to update the
application's state with the new issue. The `createIssue` function, likely
defined in a parent component like `IssueList`, would then update the
state, causing the component to re-render with the new issue added to the
list.

Additionally, the text provides an example of `onChangeStatus` function


which is called when the value of a dropdown is changed. This function
updates the state with the new value using `this.setState({ status:
e.target.value })`.

Ques: What is a REST API , and how does it differ from GraphQL?

A REST API (Representational State Transfer) is an architectural pattern


for application programming interfaces (APIs). It has gained popularity due
to its simplicity and small number of constructs.

Here's a comparison of REST and GraphQL based on the provided


content:

* **Resource Based vs. Graph Based**: REST APIs are resource-based,


using nouns (resources) as endpoints, while GraphQL is graph-based,
naturally handling relationships between objects.
* **Endpoints**: REST APIs typically have one endpoint per resource,
whereas GraphQL API servers have a single endpoint. With GraphQL, the
resource or field being accessed is part of the query itself.
* **Data Fetching**: REST APIs often return the entire object, giving the
client little control over the data received. GraphQL allows clients to
specify precisely which fields they need, improving efficiency, especially
for mobile applications.
* **Multiple API Results**: GraphQL can retrieve related and even
unrelated objects in a single API call, eliminating the need for
"aggregation" services required to bundle multiple API results in REST.
* **Type System**: GraphQL is strongly typed, allowing validation of
queries and results against a schema and providing descriptive error
messages.
* **Flexibility**: REST by itself lays down no rules for filtering, sorting,
and paginating a list of objects; specifying which fields to return;
expanding embedded objects; or specifying which fields to modify.
GraphQL was developed to address just these concerns.

In summary, REST is simpler and more widely adopted, while GraphQL


offers more control, efficiency, and flexibility in data fetching and
manipulation.

Ques: What is GraphQL, and how does it differ from a traditional


REST API?

GraphQL is a query language designed to address the shortcomings of


REST APIs. Here's a breakdown of its features and differences from
REST:

**Key Features of GraphQL:**

* **Graph-Based**: GraphQL is graph-based, making it natural to handle


relationships between objects.
* **Single Endpoint**: GraphQL API servers have a single endpoint,
unlike REST which typically has one per resource.
* **Field Specification**: Clients specify precisely what data they need,
avoiding over-fetching of data.
* **Strongly Typed**: GraphQL is strongly typed, allowing validation of
queries and results against a schema.
* **Introspection**: A GraphQL server can be queried for the types it
supports, facilitating tools and client software development.

**Differences from REST APIs:**

* **Resource vs. Graph**: REST APIs are resource-based, while


GraphQL is graph-based.
* **Multiple API Results**: GraphQL can retrieve related and even
unrelated objects in a single API call, eliminating the need for aggregation
services.
* **Data Control**: GraphQL gives clients control over the data received,
while REST often returns the entire object.
* **Flexibility**: GraphQL addresses concerns such as filtering, sorting,
specifying fields, and expanding embedded objects, which REST doesn't
explicitly define.

In essence, GraphQL offers more control, efficiency, and flexibility in data


fetching compared to REST APIs. It allows clients to request specific data,
reducing the amount of data transferred and improving performance,
especially for mobile applications.

Ques: What is “Lifting State UP” in React, and why is it useful?


Provide an example where two child components share state via
their parent.

In React, "lifting state up" refers to the process of moving the state to the
closest common ancestor of the components that need that state . This is
useful because React only allows direct data flow from parent to child via
props, and children communicate with parents via callbacks. Siblings
cannot directly communicate with each other.

**Why is it Useful?**

* **One-way Data Flow**: It enforces a clear, predictable data flow,


making the application easier to understand and debug.
* **Component Communication**: It enables communication between
components that don't have a direct parent-child relationship.
* **Data Consistency**: It ensures that all components that rely on the
same state have access to the same, up-to-date information.

**Example:**

The provided text uses the example of `IssueAdd` and `IssueTable`


components in an issue tracker application to illustrate lifting state up.

1. Initially, the `IssueTable` component might seem like the natural place
to keep the state (the list of issues).
2. However, the `IssueAdd` component also needs to interact with this
state to add new issues.
3. Since `IssueAdd` and `IssueTable` are siblings, they cannot directly
share the state.
4. To solve this, the state (the `issues` array) is "lifted up" to their common
parent, `IssueList`.
5. The `IssueList` component then passes the `issues` array down to
`IssueTable` as props, so `IssueTable` can render the list of issues.
6. When a new issue is added in `IssueAdd`, it calls a method
(`createIssue`) that is passed down as props from `IssueList` to
`IssueAdd`.
7. The `createIssue` method updates the state in `IssueList`.
8. The updated state in `IssueList` is then passed down to `IssueTable` as
props, causing `IssueTable` to re-render with the new issue.

In this example, `IssueAdd` and `IssueTable` share state (the list of


issues) via their parent, `IssueList`. The state resides in the `IssueList`
component, and the `IssueAdd` component modifies it, and the
`IssueTable` component displays it. This ensures that both components
always have access to the same, consistent data.

Ques: Describe a typical React Component hierarchy and how


components communicate with each other using props and state.

A typical React component hierarchy involves breaking down the


application into components and subcomponents, reflecting the data
model itself.

**Component Hierarchy**

* **Splitting into Components**: The UI is split into smaller, independent


pieces that can be coded and reasoned about in isolation, which makes
building and understanding complex UIs easier. Components should be
self-contained with minimal and logical interfaces to the parent.
* **Single Responsibility Principle**: Each component should be
responsible for one, and only one, thing. If a component is doing too many
things, it should be split into multiple components.
* **Granularity**: Components can be fine-grained, and larger
components can be built by putting together smaller components.

**Communication**

* **Parent to Child**: Parents communicate to children via props; when


state changes, the props automatically change.
* **Child to Parent**: Children communicate to parents via callbacks.
Access to the callback method should be explicitly given by passing it as a
prop.
* **Siblings**: Siblings and cousins can’t communicate with each other
directly; the information has to go up the hierarchy to the closest common
ancestor and then back down. This is called "lifting the state up" .
* **One-way Data Flow**: State flows as props into children, events
cause state changes, which flows back as props.
* **State and Props**: Both state and props hold model information and
affect the rendering of the component. Props are immutable, whereas
state can be changed using `this.setState()`. State variables are typically
passed down to child components as props because the children don’t
maintain or modify them.

Ques: What is GraphQL schema, and how do you use Query


Variables in a GraphQL request? Provide an example.

A GraphQL schema defines the structure of the data available in the API.
It uses a specific schema language to define types, fields, and the
relationships between them. The schema specifies the operations clients
can perform, including queries (for reading data) and mutations (for
modifying data). It also defines which fields are required and which are
optional.

**Query Variables in GraphQL**

Query variables are a way to factor dynamic values out of the query and
pass them as a separate dictionary. This is useful when the arguments to
the fields are dynamic, based on user input. Using variables avoids the
overhead of converting a template to a string and the need to escape
special characters.

**How to Use Query Variables:**

1. **Name the Operation:** Specify a name after the `query` or `mutation`


keyword. For example:

```graphql
mutation setNewMessage($message: String!) {
setAboutMessage(message: $message)
}
```

2. **Declare Variables:** Declare variables with a `$` prefix as arguments


to the operation name. Specify the variable name and its type (e.g.,
`$message: String!`). The `!` indicates a mandatory value.

3. **Replace Input Value:** Replace the static input value in the query
with the variable name.

4. **Pass Variables in JSON:** Send the variables in a separate JSON


object, distinct from the query string. The JSON object contains the
variable names (without the `$`) as properties and their corresponding
values.

**Example:**

The book provides an example of using query variables for adding a new
issue in an Issue Tracker application.

```graphql
mutation issueAdd($issue: IssueInputs!) {
issueAdd(issue: $issue) {
id
}
}
```

In this example:

* `issueAdd` is the operation name.


* `$issue` is a variable of type `IssueInputs!` (IssueInputs is an input type
containing the fields for an issue).
* The `issueAdd` field takes the `$issue` variable as an argument.

The variables are passed in the body of the `fetch()` request as a JSON
object:

```javascript
const response = await fetch('/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({ query, variables: { issue } })
});
```

Here, the `variables` property contains an object with the `issue` variable,
which holds the values for the new issue to be added.

**Benefits of Using Query Variables:**

* **Security:** Prevents SQL-injection-like issues by separating code


from data.
* **Performance:** Avoids the overhead of template string conversion.
* **Readability:** Makes queries cleaner and easier to read.
* **Maintainability:** Simplifies the process of updating dynamic values.

You might also like