Skip to content

Instantly share code, notes, and snippets.

@hugomota
Created April 21, 2020 20:29
Show Gist options
  • Save hugomota/b17725322552da71ecccb02330c1baf4 to your computer and use it in GitHub Desktop.
Save hugomota/b17725322552da71ecccb02330c1baf4 to your computer and use it in GitHub Desktop.
// 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;
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