react-redux#useSelector JavaScript Examples
The following examples show how to use
react-redux#useSelector.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BookPage.js From mern_library_nginx with MIT License | 6 votes |
BookPage = ({ match }) => {
const dispatch = useDispatch();
const bookDetails = useSelector((state) => state.bookDetails);
const { loading, error, book } = bookDetails;
useEffect(() => {
dispatch(listBookDetails(match.params.id));
}, [dispatch, match]);
return (
<>
<Link className="btn btn-success my-3" to="/books">
Go Back to My Books
</Link>
{loading ? (
<Loader />
) : error ? (
<Message variant="danger">{error}</Message>
) : (
<Row>
<Card className="my-3 p-3 rounded">
<Card.Header as="h2">
<strong>{book.title}</strong>
</Card.Header>
<Card.Body>
<Card.Subtitle className="mb-2 text-muted">
{book.subtitle}
</Card.Subtitle>
<Card.Text>{book.description}</Card.Text>
<Card.Text as="h6">ISBN {book.isbn}</Card.Text>
<Button variant="primary">{book.author}</Button>
</Card.Body>
</Card>
</Row>
)}
</>
);
}
Example #2
Source File: termsPolicyContent.js From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 | 6 votes |
export default function TermsPolicyContent(props) {
const organization = useSelector((state) => state.organization);
const { currentOrganization } = organization;
const [content, setContent] = useState('');
const dispatch = useDispatch();
const { match } = props;
useEffect(() => {
const contentType = match.params.content;
const orgDomain = match.params.organization ? match.params.organization : 'currikistudio';
if (contentType === 'tos_content') {
setContent(currentOrganization?.tos_content);
} else if (contentType === 'privacy_policy_content') {
setContent(currentOrganization?.privacy_policy_content);
}
if (!content) {
dispatch(getBranding(orgDomain));
}
});
return (
<div className="terms-policy-container" dangerouslySetInnerHTML={{ __html: content }} />
);
}
Example #3
Source File: App.js From React-discord-clone with MIT License | 6 votes |
function App() {
const dispatch = useDispatch()
const user = useSelector(selectUser)
useEffect(() => {
auth.onAuthStateChanged((authUser) => {
if (authUser) {
dispatch(login({
uid : authUser.uid,
photo: authUser.photoURL,
email: authUser.email,
displayName : authUser.displayName,
}))
}
else {
dispatch(logout())
}
})
}, [dispatch])
return (
<div className="app">
{ user ? (
<>
<Sidebar />
<Chat />
</>
) : (
<Login />
)}
</div>
);
}
Example #4
Source File: ArchivedLists.js From TrelloClone with MIT License | 6 votes |
ArchivedLists = () => {
const listObjects = useSelector((state) => state.board.board.listObjects);
const dispatch = useDispatch();
const onSubmit = async (listId) => {
dispatch(archiveList(listId, false));
};
return (
<div>
<List>
{listObjects
.filter((list) => list.archived)
.map((list, index) => (
<ListItem key={index}>
<ListItemText primary={list.title} />
<Button onClick={() => onSubmit(list._id)}>Send to Board</Button>
</ListItem>
))}
</List>
</div>
);
}
Example #5
Source File: LoginContainer.jsx From ashteki with GNU Affero General Public License v3.0 | 6 votes |
LoginContainer = () => {
const dispatch = useDispatch();
const { t } = useTranslation();
const apiState = useSelector((state) => {
const retState = state.api[Auth.LoginAccount];
if (retState && retState.status === 401) {
retState.message = t('Invalid username/password');
} else if (retState && retState.success) {
retState.message = t('Login successful, redirecting you to the home page');
setTimeout(() => {
dispatch(clearApiStatus(Auth.LoginAccount));
dispatch(authenticateSocket());
dispatch(navigate('/'));
}, 500);
}
return retState;
});
return (
<Col lg={{ span: 8, offset: 2 }}>
<Panel title={t('Login')}>
<ApiStatus
state={apiState}
onClose={() => dispatch(clearApiStatus(Auth.LoginAccount))}
/>
<Login onSubmit={(values) => dispatch(loginAccount(values))} />
</Panel>
</Col>
);
}
Example #6
Source File: MapOverlay.js From foster-together-fe with MIT License | 6 votes |
export default function MapThing() {
const dispatch = useDispatch();
useEffect(() => {
dispatch(getMembers());
}, [dispatch]);
const locations = useSelector(state => state.mem);
const [points, setPoints] = useState(locations.membersArray);
const [selected, setSelected] = useState({});
return (
<>
<NavBar />
<PageContain>
<MapFilters filter={setPoints} locations={locations.membersArray} />
<Map locations={points} selected={selected} setSelected={setSelected} />
<PersonInfo selected={selected} />
</PageContain>
</>
);
}
Example #7
Source File: BioCard.js From grants-fe with MIT License | 6 votes |
BioCard = ({ profileDetails }) => {
const classes = useStyles();
const userType = useSelector((state) => state.login.usertype);
return (
<>
<Grid className={classes.biosection}>
{!profileDetails.org_name || profileDetails.org_name === "" ? (
<h1>
{profileDetails.first_name} {profileDetails.last_name}{" "}
</h1>
) : (
<h1>{profileDetails.org_name}</h1>
)}
{userType === "applicant" && (
<h2>Sector: {profileDetails.sector}</h2>
)}
</Grid>
<Paper className={classes.profilepaper}>
<p>{profileDetails.bio}</p>
</Paper>
</>
);
}
Example #8
Source File: UserList.js From neighborhood-chef-fe with MIT License | 6 votes |
UserList = ({ event, filteredList }) => {
const invitedList = useSelector((state) => state.inviteList);
return (
<>
{invitedList
.sort((a, b) => a.firstName.localeCompare(b.firstName))
.map((user) => {
return (
Number(user.id) !== event.user_id && (
<InvitedUser key={user.id} user={user} />
)
);
})}
{filteredList
.sort((a, b) => a.firstName.localeCompare(b.firstName))
.map((user) => {
return (
Number(user.id) !== event.user_id && (
<UninvitedUser key={user.id} user={user} />
)
);
})}
</>
);
}
Example #9
Source File: index.js From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 | 5 votes |
ActivityPreviewCard = (props) => {
const {
showLti,
shared,
activity,
projectId,
playlistId,
playlist,
teamPermission,
} = props;
const organization = useSelector((state) => state.organization);
return (
<div className="preview-activity-dropdown">
<Link
to={
shared
? `/project/${projectId}/playlist/${playlistId}/activity/${activity.id}/preview/shared`
: showLti
? `/playlist/${playlistId}/activity/${activity.id}/preview/lti`
: `/org/${organization.currentOrganization?.domain}/project/${projectId}/playlist/${playlistId}/activity/${activity.id}/preview`
}
>
<li className="check">
{activity.thumb_url && (
<div
className="bg-thumbnail"
style={{
backgroundImage: activity.thumb_url.includes("pexels.com")
? `url(${activity.thumb_url})`
: `url(${global.config.resourceUrl}${activity.thumb_url})`,
}}
/>
)}
<div style={{ maxWidth: "253px" }}>
<div className="title">{activity.title}</div>
</div>
</li>
</Link>
{!showLti && (
<DropdownActivity
resource={activity}
playlist={playlist}
teamPermission={teamPermission || {}}
/>
)}
</div>
);
}
Example #10
Source File: Counter.js From React-discord-clone with MIT License | 5 votes |
export function Counter() {
const count = useSelector(selectCount);
const dispatch = useDispatch();
const [incrementAmount, setIncrementAmount] = useState('2');
return (
<div>
<div className={styles.row}>
<button
className={styles.button}
aria-label="Increment value"
onClick={() => dispatch(increment())}
>
+
</button>
<span className={styles.value}>{count}</span>
<button
className={styles.button}
aria-label="Decrement value"
onClick={() => dispatch(decrement())}
>
-
</button>
</div>
<div className={styles.row}>
<input
className={styles.textbox}
aria-label="Set increment amount"
value={incrementAmount}
onChange={e => setIncrementAmount(e.target.value)}
/>
<button
className={styles.button}
onClick={() =>
dispatch(incrementByAmount(Number(incrementAmount) || 0))
}
>
Add Amount
</button>
<button
className={styles.asyncButton}
onClick={() => dispatch(incrementAsync(Number(incrementAmount) || 0))}
>
Add Async
</button>
</div>
</div>
);
}
Example #11
Source File: ArchivedCards.js From TrelloClone with MIT License | 5 votes |
ArchivedCards = () => {
const cards = useSelector((state) => state.board.board.cardObjects);
const lists = useSelector((state) => state.board.board.listObjects);
const dispatch = useDispatch();
const onDelete = async (listId, cardId) => {
dispatch(deleteCard(listId, cardId));
};
const onSendBack = async (cardId) => {
dispatch(archiveCard(cardId, false));
};
return (
<div>
<List>
{cards
.filter((card) => card.archived)
.map((card, index) => (
<ListItem key={index} className='archived-card'>
<Card>
<CardContent>{card.title}</CardContent>
</Card>
<div>
<Button
color='secondary'
onClick={() =>
onDelete(
lists.find((list) => list.cards.includes(card._id))._id,
card._id
)
}
>
Delete Card
</Button>
<Button onClick={() => onSendBack(card._id)}>Send to List</Button>
</div>
</ListItem>
))}
</List>
</div>
);
}
Example #12
Source File: PasswordGame.jsx From ashteki with GNU Affero General Public License v3.0 | 5 votes |
PasswordGame = () => {
const { t } = useTranslation();
const { passwordError, passwordJoinType, passwordGame } = useSelector((state) => ({
passwordError: state.lobby.passwordError,
passwordGame: state.lobby.passwordGame,
passwordJoinType: state.lobby.passwordJoinType
}));
const [password, setPassword] = useState('');
const dispatch = useDispatch();
if (!passwordGame) {
return null;
}
return (
<div>
<Panel title={passwordGame.name}>
{passwordError && <AlertPanel type='danger' message={t(passwordError)} />}
<h3>
<Trans>Enter the password</Trans>
</h3>
<div className='mt-1 mb-3'>
<input
className='form-control'
type='text'
onChange={(event) => setPassword(event.target.value)}
value={password}
/>
</div>
<div className='text-center'>
<Button
variant='primary'
onClick={() => {
dispatch(
sendSocketMessage(
passwordJoinType === 'Join' ? 'joingame' : 'watchgame',
passwordGame.id,
password
)
);
}}
>
{t(passwordJoinType)}
</Button>
<Button variant='danger' onClick={() => dispatch(cancelPasswordJoin())}>
<Trans>Cancel</Trans>
</Button>
</div>
</Panel>
</div>
);
}
Example #13
Source File: StripeButton.js From Merch-Dropper-fe with MIT License | 5 votes |
StripeCheckoutButton = ({ price, domain, history }) => {
const priceForStripe = price * 100;
const publishableKey = "pk_test_BMXGPoL1peDqHyy42iFEoAMg00l0M6PNex";
//const publishableKey = 'pk_live_3zwsNFDgIC2nJd4h7F9Y5K8s00exa06IRd'; //Uncomment this line for when stripe is collecting Live payments. Make sure to also change the environment variable on the Backend to the Live key.
// WE COULD ALSO keep the test key and make a if/else like we have done with the urls so that it stays in test mode during development
let config = {
headers: {
"Content-Type": "application/json"
}
};
// grabs the orderToken to complete payment process and send to backend calculate application fee
const tokenSelector = useSelector(state => state.QuoteReducer.quote)
const onToken = token => {
token.domain_name = domain;
token.orderToken = tokenSelector.quote.orderToken;
axiosWithEnv()
.post("/api/payments", {
amount: priceForStripe,
token,
config,
})
.then(res => {
alert("payment successful");
//history.push("/products");
history.push(`/${domain}`);
})
.catch(error => {
console.dir("payment error", error);
alert("There was an issue with your payment.");
history.push(`${token.domain_name}/checkout`)
});
};
return (
<StripeCheckout
label="Finish Checkout"
name="MerchDropper"
billingAddress={true}
shippingAddress={false}
zipCode={true}
currency='USD'
image={`${MerchDropperLogo}`} // might be cause of 400 stripe bug
description={`Your total is $${price}`}
amount={priceForStripe}
panelLabel="Pay Now"
token={onToken}
stripeKey={publishableKey}
/>
);
}
Example #14
Source File: ProfilePageReview.js From allay-fe with MIT License | 5 votes |
ProfilePageReview = ({ userReviews }) => {
const isLoading = useSelector((state) => state.user.isLoading)
const under = { textDecoration: 'underline' }
return (
<Flex justify="center" mt=".5%" mb="2%">
{!isLoading ? (
<Box
width="1048px"
style={{ border: '1px solid #e6e5e5', padding: '3%' }}
>
{userReviews && userReviews.length > 0 ? (
userReviews.map((review) => {
const postedOn = dateConvert(review.created_at)
return (
<AccordionItem
key={review.review_id}
width="816px"
style={{ margin: '0 auto' }}
>
<AccordionHeader
style={{ borderRadius: '10px ' }}
_expanded={{ bg: '#007F00', color: 'white' }}
>
<Box flex="1" textAlign="left">
<span
style={{
borderRadius: '35%',
backgroundColor: '#a5a5a5',
padding: '.5%',
}}
>
Interview
</span>{' '}
posted at {postedOn}
</Box>
<AccordionIcon />
</AccordionHeader>
<AccordionPanel>
<h6>
<i style={under}>{review.work_status}</i> at{' '}
<i style={under}>{review.company_name}</i> in{' '}
<i style={under}>{review.city}</i>
</h6>
</AccordionPanel>
<AccordionPanel>
<h5>Review:</h5> <span>{review.comment}</span>
</AccordionPanel>
</AccordionItem>
)
})
) : (
<span>no reviews</span>
)}
</Box>
) : null}
</Flex>
)
}
Example #15
Source File: AdminDashboard.js From foster-together-fe with MIT License | 5 votes |
export default function Distance() {
const dispatch = useDispatch();
useEffect(() => {
dispatch(getMembers());
}, [dispatch]);
const { membersArray } = useSelector(state => state.mem);
// Functions to display taskbar //
const numApplications = membersArray.filter(
people => people.application === 1
);
const numVolunteers = membersArray.filter(
people => people.type === "neighbors"
);
const familiesToMatch = membersArray.filter(
people => people.type === "families"
);
return (
<>
<Navigation />
<DashContainer>
<Welcome />
<TaskBar
members={membersArray}
numApplications={numApplications}
numVolunteers={numVolunteers}
familiesToMatch={familiesToMatch}
/>
<SearchBar members={membersArray} />
<TableContain>
<MemberTable members={membersArray} />
</TableContain>
</DashContainer>
</>
);
}
Example #16
Source File: App.js From grants-fe with MIT License | 5 votes |
//
function App() {
const loggedIn = useSelector((state) => state.login.loggedIn);
const user = useSelector((state) => state.login.user);
const userType = useSelector((state) => state.login.usertype);
const userId = useSelector((state) => state.login.userId);
const grants = useSelector((state) => state.grants.applicantGrants);
const dispatch = useDispatch();
useEffect(() => {
//only fetches grants if a userId exists and grants have not already been fetched
if (userId !== undefined && grants && grants.length === 0) {
dispatch(getGrants());
}
}, [dispatch, userId, grants]);
return (
<Router>
<ThemeProvider theme={theme}>
<Route exact path="/">
<LandingPage />
</Route>
{loggedIn && <Navbar />}
<Switch>
<PrivateRoute
path="/writer-favorites"
component={WritersFavoriteGrants}
/>
<PrivateRoute path="/EditGrant/:id" component={UpdateGrant} />
<PrivateRoute path="/GrantsForm" component={GrantsForm} />
<PrivateRoute path="/GrantsList" component={GrantsList} />
{userType && userType === "applicant" ? (
<PrivateRoute path="/profile" component={ApplicantProfile} />
) : (
<PrivateRoute path="/profile" component={WriterProfile} />
)}
<PrivateRoute path="/Homepage" component={Homepage} />
{user && user.user_type === "applicant" ? (
<PrivateRoute path="/onboarding" component={ApplicantProfileForm} />
) : (
<PrivateRoute path="/onboarding" component={WriterProfileForm} />
)}
<Route path="/RegisterForm">
<RegisterForm />
</Route>
<Route path="/LoginForm">
<LoginForm />
</Route>
<PrivateRoute exact path="/Grants" component={GrantsPage} />
</Switch>
</ThemeProvider>
</Router>
);
}
Example #17
Source File: CreateEventHeader.js From neighborhood-chef-fe with MIT License | 5 votes |
CreateEventHeader = () => {
const page = useSelector((state) => state.page);
return (
<div className="createFormHeaderContainer">
<div
className={`createFormHeaderNotActive${
page === 1 ? " createFormHeaderActive" : ""
}`}
>
<Icon
icon={pencilIcon}
style={{ fontSize: "2.5rem", marginRight: "5px" }}
/>
<h3>Details</h3>
</div>
<div
className={`createFormHeaderNotActive${
page === 2 ? " createFormHeaderActive" : ""
}`}
>
<Icon
icon={shapeOutline}
style={{ fontSize: "2.5rem", marginRight: "5px" }}
/>
<h3>Preferences</h3>
</div>
<div
className={`createFormHeaderNotActive${
page === 3 ? " createFormHeaderActive" : ""
}`}
>
<Icon
icon={createIcon}
style={{ fontSize: "2.5rem", marginRight: "5px" }}
/>
<h3>Create</h3>
</div>
<div
className={`createFormHeaderNotActive${
page === 4 ? " createFormHeaderActive" : ""
}`}
>
<Icon
icon={shareIcon}
style={{ fontSize: "2.5rem", marginRight: "5px" }}
/>
<h3>Share</h3>
</div>
</div>
);
}
Example #18
Source File: BookListPage.js From mern_library_nginx with MIT License | 4 votes |
BookListPage = ({ history }) => {
const [title, setTitle] = useState("");
const [subtitle, setSubTitle] = useState("");
const [author, setAuthor] = useState("");
const [description, setDescription] = useState("");
const [isbn, setISBN] = useState("");
const dispatch = useDispatch();
const bookList = useSelector((state) => state.bookList);
const { loading, error, books } = bookList;
const bookCreate = useSelector((state) => state.bookCreate);
const {
loading: loadingCreate,
error: errorCreate,
success: successCreate,
book: createdBook,
} = bookCreate;
const bookDelete = useSelector((state) => state.bookDelete);
const {
loading: loadingDelete,
error: errorDelete,
success: successDelete,
} = bookDelete;
useEffect(() => {
dispatch({ type: BOOK_CREATE_RESET });
if (successCreate) {
history.push(`/books/${createdBook._id}`);
} else {
dispatch(listBooks());
}
}, [dispatch, history, successCreate, successDelete, createdBook]);
const createBookHandler = (e) => {
e.preventDefault();
dispatch(
createBook({
title,
subtitle,
description,
author,
isbn,
})
);
};
const deleteHandler = (id) => {
dispatch(deleteBook(id));
};
return (
<>
{loadingCreate && <Loader />}
{errorCreate && <Message variant="danger">{errorCreate}</Message>}
{loadingDelete && <Loader />}
{errorDelete && <Message variant="danger">{errorDelete}</Message>}
<Row>
<Col>
<Form onSubmit={createBookHandler}>
<Form.Group controlId="bookTitle">
<Form.Label>Book Title</Form.Label>
<Form.Control
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Enter Title"
/>
</Form.Group>
<Form.Group controlId="bookSubTitle">
<Form.Label>Book Sub-Title</Form.Label>
<Form.Control
type="text"
value={subtitle}
onChange={(e) => setSubTitle(e.target.value)}
placeholder="Enter Sub title"
/>
</Form.Group>
<Form.Group controlId="bookAuthor">
<Form.Label>Author</Form.Label>
<Form.Control
type="text"
value={author}
onChange={(e) => setAuthor(e.target.value)}
placeholder="Enter an Author"
/>
</Form.Group>
<Form.Group controlId="bookDescription">
<Form.Label>Description</Form.Label>
<Form.Control
type="text"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Enter Description"
/>
</Form.Group>
<Form.Group controlId="bookISBN">
<Form.Label>ISBN Number</Form.Label>
<Form.Control
type="text"
value={isbn}
onChange={(e) => setISBN(e.target.value)}
placeholder="Enter ISBN Number"
/>
</Form.Group>
<Button
variant="warning"
type="submit"
onClick={createBookHandler}
size="lg"
block
>
<i className="fas fa-plus"></i> Create Book
</Button>
</Form>
</Col>
</Row>
<Row>
<Col className="p-5">
<h1>The Books in My Library </h1>
</Col>
</Row>
{loading ? (
<Loader />
) : error ? (
<Message variant="danger">{error}</Message>
) : (
<>
<Row>
{books.map((book) => (
<Col key={book._id} sm={12} md={6} lg={4}>
<Book book={book} deleteHandler={deleteHandler} />
</Col>
))}
</Row>
</>
)}
</>
);
}
Example #19
Source File: index.js From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 | 4 votes |
ActivityCard = (props) => {
const { activity, projectId, playlistId, lti, sampleID, setModalShow, setCurrentActivity, playlist, shared } = props;
const organization = useSelector((state) => state.organization);
return (
<>
{/* <li className="preview-list-update">
{sampleID ? (
<a
onClick={() => {
setCurrentActivity(activity.id);
setModalShow(true);
}}
>
<div
className="playimg"
style={{
backgroundImage:
!!activity.thumb_url &&
activity.thumb_url.includes("pexels.com")
? `url(${activity.thumb_url})`
: `url(${global.config.resourceUrl}${activity.thumb_url})`,
}}
/>
<div className="plydet">
{activity.metadata ? activity.metadata.title : activity.title}
</div>
</a>
) : (
<>
<Link
to={
lti
? `/playlist/${playlistId}/activity/${activity.id}/preview/lti`
: `/org/${organization.currentOrganization?.domain}/project/${projectId}/playlist/${playlistId}/activity/${activity.id}/preview`
}
onClick={() => localStorage.setItem("projectPreview", true)}
>
<div
className="playimg playimage-update"
style={{
backgroundImage:
!!activity.thumb_url &&
activity.thumb_url.includes("pexels.com")
? `url(${activity.thumb_url})`
: `url(${global.config.resourceUrl}${activity.thumb_url})`,
}}
/>
<div className="plydet plydet-update">
{activity.metadata ? activity.metadata.title : activity.title}
</div>
</Link>
</>
)}
</li> */}
<li className="preview-list-update">
{sampleID ? (
<a
onClick={() => {
setCurrentActivity(activity.id);
setModalShow(true);
}}
>
<div
className="sharedActivityImage"
style={{
backgroundImage:
!!activity.thumb_url && activity.thumb_url.includes('pexels.com') ? `url(${activity.thumb_url})` : `url(${global.config.resourceUrl}${activity.thumb_url})`,
}}
/>
<div className="textSharedActivity">{activity.metadata ? activity.metadata.title : activity.title}</div>
</a>
) : (
<>
<Link
to={
shared
? `/project/${projectId}/playlist/${playlistId}/shared?view=activity`
: lti
? `/playlist/${playlistId}/activity/${activity.id}/preview/lti?view=activity`
: `/org/${organization.currentOrganization?.domain}/project/${projectId}/playlist/${playlistId}/activity/${activity.id}/preview?view=activity`
}
onClick={() => localStorage.setItem('projectPreview', true)}
>
<div className="playimage-update-mobile">
<div
className="playimg playimage-update"
style={{
backgroundImage:
!!activity.thumb_url && activity.thumb_url.includes('pexels.com') ? `url(${activity.thumb_url})` : `url(${global.config.resourceUrl}${activity.thumb_url})`,
}}
/>
<div className="plydet plydet-update" id="plydet-update-id">
{activity.metadata ? activity.metadata.title : activity.title}
</div>
</div>
</Link>
{/* {!lti && (
<div className="activity-options-wrapper check">
<ResourceCardDropdown
playlist={playlist}
resource={activity}
teamPermission={teamPermission || {}}
previewPage="projectPreview"
/>
</div>
)} */}
</>
)}
</li>
</>
);
}