Skip to content

Commit

Permalink
5. Class-based Components & Context
Browse files Browse the repository at this point in the history
  • Loading branch information
sofiane-abou-abderrahim committed Apr 13, 2024
1 parent 573c0ae commit f369d81
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 10 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,10 @@
2. use the `componentDidUpdate()` lifecycle to handle side effects and replace `useEffect()`
3. use `componentDidMount()` to simulate a case where the data comes from an http request
4. use `componentWillUnmount()` in `User.js`

## 5. Class-based Components & Context

1. add a new `users-context.js`
2. use context with the first approach: the context `Consumer` component by adding `<UsersContext.Consumer>` in `UserFinder.js`
3. or use `static contextType` in `UserFinder.js`
4. now access the context with `this.context.users` instead of `DUMMY_USERS`
15 changes: 13 additions & 2 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
import UserFinder from './components/UserFinder';
import UsersContext from './store/users-context';

const DUMMY_USERS = [
{ id: 'u1', name: 'Max' },
{ id: 'u2', name: 'Manuel' },
{ id: 'u3', name: 'Julie' }
];

function App() {
const usersContext = {
users: DUMMY_USERS
};

return (
<div>
<UsersContext.Provider value={usersContext}>
<UserFinder />
</div>
</UsersContext.Provider>
);
}

Expand Down
13 changes: 5 additions & 8 deletions src/components/UserFinder.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,11 @@ import { Fragment, useState, useEffect, Component } from 'react';

import Users from './Users';
import classes from './UserFinder.module.css';

const DUMMY_USERS = [
{ id: 'u1', name: 'Max' },
{ id: 'u2', name: 'Manuel' },
{ id: 'u3', name: 'Julie' }
];
import UsersContext from '../store/users-context';

class UserFinder extends Component {
static contextType = UsersContext;

constructor() {
super();
this.state = {
Expand All @@ -20,13 +17,13 @@ class UserFinder extends Component {

componentDidMount() {
// Send http request...
this.setState({ filteredUsers: DUMMY_USERS });
this.setState({ filteredUsers: this.context.users });
}

componentDidUpdate(prevProps, prevState) {
if (prevState.searchTerm !== this.state.searchTerm) {
this.setState({
filteredUsers: DUMMY_USERS.filter(user =>
filteredUsers: this.context.users.filter(user =>
user.name.includes(this.state.searchTerm)
)
});
Expand Down
7 changes: 7 additions & 0 deletions src/store/users-context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import React from 'react';

const UsersContext = React.createContext({
users: []
});

export default UsersContext;

0 comments on commit f369d81

Please sign in to comment.