Created
April 21, 2020 20:29
-
-
Save hugomota/b17725322552da71ecccb02330c1baf4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// import the hook | |
import React, { useContext } from "react"; | |
//Import the Context | |
import { UsersContext } from "./context"; | |
// get the current value in UsersContext through the hook | |
const usersContext = useContext(UsersContext); | |
const { users, selectedUser, setSelectedUser } = usersContext; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { createContext, useState } from "react"; | |
import PropTypes from "prop-types"; | |
export const Context = createContext({}); | |
export const Provider = props => { | |
// Initial values are obtained from the props | |
const { | |
users: initialUsers, | |
selectedUser: initialSelectedUsers, | |
children | |
} = props; | |
// Use State to keep the values | |
const [users, setUsers] = useState(initialUsers); | |
const [selectedUser, setSelectedUser] = useState(initialSelectedUsers); | |
const addNewUser = userName => { | |
const newUser = { id: new Date().getTime().toString(), name: userName }; | |
setUsers(users.concat([newUser])); | |
}; | |
// Make the context object: | |
const usersContext = { | |
users, | |
setUsers, | |
selectedUser, | |
setSelectedUser, | |
addNewUser | |
}; | |
// pass the value in provider and return | |
return <Context.Provider value={usersContext}>{children}</Context.Provider>; | |
}; | |
export const { Consumer } = Context; | |
Provider.propTypes = { | |
users: PropTypes.array, | |
selectedUser: PropTypes.object | |
}; | |
Provider.defaultProps = { | |
users: [], | |
selectedUser: {} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment