lodash#first JavaScript Examples
The following examples show how to use
lodash#first.
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: enhancers.js From plant-3d-explorer with GNU Affero General Public License v3.0 | 6 votes |
export function ifNotNil (fn) {
return function (...args) {
if (filter(args, [null, undefined, false]).length) {
return fn(...args)
} else {
return args.length === 1
? first(args)
: args
}
}
}
Example #2
Source File: ProductView.js From web with MIT License | 5 votes |
ProductView = ({ data }) => {
const product = data.sanityProduct;
const products = data.allSanityProduct.edges;
const home = data.sanitySiteSettings;
const reviews = data.allSanityReview.edges;
const [variant, setVariant] = useState({});
// console.log('variant', variant);
useEffect(() => {
const firstItem = first(product.otherVariants);
if (firstItem) {
setVariant(firstItem);
}
}, [product.otherVariants]);
const metaImage = variant.featuredImage
? variant.featuredImage.asset.fluid.src
: `${config.logo}`;
return (
<Layout>
<Seo
title={product.title}
description={`Buy by ${product.title} at ${config.siteName}`}
url={`${config.siteUrl}/product/${product.slug.title}`}
image={metaImage}
isProduct
/>
<div className="container">
<section className="section">
<Container className="columns">
<div className="column">
<ProductGallery variant={variant} />
</div>
<div className="column section">
<ProductInfo
home={home}
product={product}
reviews={reviews}
variant={variant}
setVariant={setVariant}
/>
</div>
</Container>
</section>
</div>
<ProductSpecs product={product} variant={variant} />
<ProductReviews reviews={reviews} />
<div className="container">
<ProductsList title="We think you'll" products={products} />
<div className="has-text-centered ">
<ViewAllBtn to="/shop" className="button is-outlined is-medium">
View all
</ViewAllBtn>
</div>
</div>
</Layout>
);
}
Example #3
Source File: index.js From plant-3d-explorer with GNU Affero General Public License v3.0 | 5 votes |
export default function GraphPanel (props) {
const [hoveredAngle] = useHoveredAngle()
const [selectedAngle] = useSelectedAngle()
const highlightedAngle = first([hoveredAngle, selectedAngle]
.filter((value) => ((value !== null) && (value !== undefined))))
if (!props.data.automated || props.data.automated.length === 0) return null
const ifManualData = !!props.data.manual
const ifHighligthed = highlightedAngle !== null && highlightedAngle !== undefined
const valueTransformFn = (props.data.valueTransform || ((v) => v))
return <Container>
<Header
id={props.id}
tooltipId={props.tooltipId}
onClose={props.onClose}
ifManualData={ifManualData}
ifHighligthed={ifHighligthed}
ifGraph={props.ifGraph}
data={props.data}
automatedValue={
ifHighligthed
? (props.data.automated[highlightedAngle] !== null && props.data.automated[highlightedAngle] !== undefined)
? valueTransformFn(props.data.automated[highlightedAngle]).toFixed(0) + ` ${props.data.unit}`
: ''
: ''
}
manualValue={
!!props.data.manual && ifHighligthed
? (props.data.manual[highlightedAngle] !== null && props.data.manual[highlightedAngle] !== undefined)
? valueTransformFn(props.data.manual[highlightedAngle]).toFixed(0) + ` ${props.data.unit}`
: ''
: ''
}
/>
<Graph
unit={props.data.unit}
data={props.data}
ifManualData={ifManualData}
valueTransformFn={valueTransformFn}
/>
</Container>
}
Example #4
Source File: index.js From nextjs-todo-list with MIT License | 4 votes |
HomeContainer = ({ firebase, user }) => {
const [currentTab, setCurrentTab] = useState(0);
const [loading, setLoading] = useState(false);
const [team, setTeam] = useState(null);
const [userTodos, setUserTodos] = useState([]);
const handleChangeTab = (event, newValue) => {
setCurrentTab(newValue);
};
const completeTeamMembersData = async (teamObj) => {
const memberPromises = [];
const { members } = teamObj;
members.forEach((member) => {
memberPromises.push(member.get());
});
const memebersData = await Promise.all(memberPromises);
if (memebersData && memebersData.length > 0) {
memebersData.forEach((member, index) => {
members[index] = member.data();
});
}
return members;
};
async function fetchData() {
setLoading(true);
const teams = await firebase.getCollectionData({
collection: 'teams',
where: { field: 'author', op: '==', value: user.uid },
});
const ownedTeam = first(teams);
if (!isEmpty(ownedTeam)) {
if (ownedTeam.members.length > 0) {
const teamMembers = await completeTeamMembersData(ownedTeam);
ownedTeam.membersData = teamMembers;
}
setTeam(ownedTeam);
}
setLoading(false);
}
async function fetchJoinedData() {
setLoading(true);
const joinedTeam = await firebase.getDocumentData({
collection: 'teams',
documentId: user.team,
});
if (!isEmpty(joinedTeam)) {
if (joinedTeam.members.length > 0) {
const teamMembers = await completeTeamMembersData(joinedTeam);
joinedTeam.membersData = teamMembers;
}
setTeam(joinedTeam);
}
setLoading(false);
}
const handleAddTodo = (addTodo, text) => {
const newTodo = { id: addTodo.id, text, completed: false, editable: false };
// Add todo to the beginnning of array
userTodos.unshift(newTodo);
setUserTodos(userTodos);
};
// To fetch team data
useEffect(() => {
if (isEmpty(user.team)) {
fetchData();
} else if (!isEmpty(user.team)) {
fetchJoinedData();
}
}, []);
// To fetch TODOS data
useEffect(() => {
async function fetchTodosData() {
setLoading(true);
let todos = await firebase.getCollectionData({
collection: 'todos',
where: { field: 'author', op: '==', value: user.uid },
});
todos = todos.map((todo) => {
return { ...todo, editable: false };
});
console.log({ todos });
setUserTodos(todos);
setLoading(false);
}
fetchTodosData();
}, []);
// To fetch realtime task assigned
useEffect(() => {
const unsubscribe = firebase.db.collection('todos').onSnapshot((snapshot) => {
if (!snapshot.empty) {
const myDataArray = [];
snapshot.forEach((doc) => {
const rtTodo = doc.data();
// If has been assigned to auth user
if (rtTodo.assigning && rtTodo.author === user.uid) {
myDataArray.push({ ...rtTodo });
const rtTodoRef = firebase.getRef({ collection: 'todos', doc: doc.id });
// Update flag
rtTodoRef.update({ assigning: false });
// Update current state
handleAddTodo(rtTodo, rtTodo.text);
}
});
}
});
return () => {
unsubscribe();
};
}, [firebase]);
if (loading)
return (
<div className="loading-container">
<h2>Loading Application...</h2>
<CircularProgress size={68} />
<style jsx>
{`
.loading-container {
width: 100%;
height: 80%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
`}
</style>
</div>
);
return (
<Container maxWidth="md">
<AppBar position="static" color="white">
<Tabs
value={currentTab}
indicatorColor="primary"
textColor="primary"
onChange={handleChangeTab}
aria-label="tabs"
centered
>
<Tab label="My tasks" icon={<PersonIcon />} {...a11yProps(0)} />
<Tab label="My Team" icon={<PeopleIcon />} {...a11yProps(1)} />
</Tabs>
</AppBar>
<TabPanel value={currentTab} index={0}>
<TodoContainer
items={userTodos}
firebase={firebase}
team={team}
user={user}
onSetTodo={(items) => setUserTodos(items)}
onAddTodo={handleAddTodo}
/>
</TabPanel>
<TabPanel value={currentTab} index={1}>
<TeamContainer
firebase={firebase}
team={team}
user={user}
onSetTeam={(payloadTeam) => setTeam(payloadTeam)}
/>
</TabPanel>
</Container>
);
}
Example #5
Source File: index.js From nextjs-todo-list with MIT License | 4 votes |
TeamContainer = memo(({ firebase, team, user, onSetTeam }) => {
const { updateUser } = useContext(AuthContext);
const [progress, setProgress] = useState(false);
const { enqueueSnackbar } = useSnackbar();
const completeTeamMembersData = async (teamObj) => {
const memberPromises = [];
const { members } = teamObj;
members.forEach((member) => {
memberPromises.push(member.get());
});
const memebersData = await Promise.all(memberPromises);
if (memebersData && memebersData.length > 0) {
memebersData.forEach((member, index) => {
members[index] = member.data();
});
}
return members;
};
const handleCreateTeam = async (teamName) => {
setProgress(true);
const teamCode = new Date().getUTCMilliseconds();
// Fetch auth user ref
const authRef = await firebase.authRef();
const teamToServer = {
author: user.uid,
name: teamName,
code: teamCode,
members: [authRef],
createdAt: new Date(),
};
const todoAdded = await firebase.saveData({ collection: 'teams', data: teamToServer });
// Add team to user collection
authRef.update({ team: todoAdded.id });
// Update local saved user
// eslint-disable-next-line no-param-reassign
user.team = todoAdded.id;
if (todoAdded.members.length > 0) {
await completeTeamMembersData(todoAdded);
}
updateUser(user);
onSetTeam(todoAdded);
setProgress(false);
};
const handleJoinTeam = async (teamCode) => {
setProgress(true);
const teams = await firebase.getCollectionData({
collection: 'teams',
where: { field: 'code', op: '==', value: teamCode },
addRef: true,
});
const foundTeam = first(teams);
if (!isEmpty(foundTeam)) {
// Fetch auth user ref
const authRef = await firebase.authRef();
// Fetch document ref
const teamRef = await firebase.getRef({ collection: 'teams', doc: foundTeam.id });
foundTeam.members.push(authRef);
teamRef.update({ members: foundTeam.members });
// Add team to user collection
authRef.update({ team: foundTeam.id });
// Update local saved user
// eslint-disable-next-line no-param-reassign
user.team = foundTeam.id;
if (foundTeam.members.length > 0) {
await completeTeamMembersData(foundTeam);
}
updateUser(user);
onSetTeam(foundTeam);
} else {
enqueueSnackbar('Team not found, review the team code', { variant: 'error' });
}
setProgress(false);
};
if (isEmpty(team)) {
return (
<EmptyTeam onCreateTeam={handleCreateTeam} onJoinTeam={handleJoinTeam} loading={progress} />
);
}
return <UserTeam team={team} />;
})
Example #6
Source File: graph.js From plant-3d-explorer with GNU Affero General Public License v3.0 | 4 votes |
Chart = sceneWrapper(({ valueTransformFn, ifManualData, data, unit, containerWidth, containerHeight }) => {
const [hoveredAngle, setHoveredAngle] = useHoveredAngle()
const [selectedAngle, setSelectedAngle] = useSelectedAngle()
const [colors] = useColor()
const height = containerHeight - (37 * 1.6)
const goal = data.goal
const vertiaclTickNb = Math.max(
data.fruitPoints.length,
data.automated.length,
(data.manual ? data.manual.length : 0)
)
const nb = vertiaclTickNb - 1 // intermediate variable used when creating the Array to plot angles and internodes sequences with the correct size
const verticalTicks = Array(Math.ceil(vertiaclTickNb / 5))
.fill()
.map((_, i) => (i * 5) - (i !== 0 ? 1 : 0))
.filter((d) => (vertiaclTickNb - d) > 3)
// .concat(data.fruitPoints.length - 1)
.concat(vertiaclTickNb - 1)
verticalScale
.domain([first(verticalTicks), last(verticalTicks)])
.rangeRound([height, 5])
const horizontalTicks = data.bounds
horizontalScale
.domain([first(horizontalTicks), last(horizontalTicks)])
.rangeRound([0, containerWidth - 37])
const barHeight = Math.floor(height / vertiaclTickNb)
const points = data.automated
.map((rad, i) => {
return {
datum: rad,
x: horizontalScale(valueTransformFn(rad)) + pointsOffset,
y: verticalScale(i)
}
})
const manualPoints = (!ifManualData ? [] : data.manual)
.map((rad, i) => {
return {
x: horizontalScale(valueTransformFn(rad)) + pointsOffset,
y: verticalScale(i)
}
})
const highligthed = [hoveredAngle, selectedAngle]
.filter((d) => isNotNullAndUndefiend(d))
.filter((d) => d < vertiaclTickNb)[0]
return <Content>
<TopPart>
<HorizontalAxis>
{
horizontalTicks.map((index) => {
return <HorizontalTick
key={`horizontal-tick-${index}`}
left={horizontalScale(index) + 34}
>
<span>
{index} {unit}
</span>
</HorizontalTick>
})
}
{
isNotNullAndUndefiend(goal) && <GoalHorizontalTick
key={'horizontal-tick-goal'}
left={horizontalScale(goal) + 34}
>
<span>
{goal} {unit}
</span>
</GoalHorizontalTick>
}
</HorizontalAxis>
<GraphPart>
<VerticalAxis>
{
verticalTicks.map((index) => {
return <VerticalTick
key={`vertical-tick-${index}`}
top={verticalScale(index)}
>
{index + 1}
</VerticalTick>
})
}
</VerticalAxis>
<SVG
width={containerWidth - 37 + 5}
height={height}
>
<Area d={area(points)} />
<g>
<Line d={line(points)} />
{
points.map((d, index) => {
return <Point
key={`point-${index}`}
cx={d.x}
cy={d.y}
/>
})
}
</g>
{
ifManualData && <g>
<Line d={line(manualPoints)} red />
{
manualPoints.map((d, index) => {
return <Point
red
key={`manual-point-${index}`}
cx={d.x}
cy={d.y}
/>
})
}
</g>
}
{
isNotNullAndUndefiend(goal) && <GoalLine
x1={horizontalScale(goal)}
x2={horizontalScale(goal)}
y1={0}
y2={height}
/>
}
</SVG>
</GraphPart>
</TopPart>
<InteractorContainer
width={containerWidth - 37}
height={height}
onMouseLeave={() => setHoveredAngle(null)}
>
{
new Array(nb)
.fill()
.map((_, i) => {
const d = points[i] || manualPoints[i]
return <Interactor
key={`interactor-${i}`}
top={d.y - (barHeight * 0.5)}
height={barHeight}
selectedAngle={isNotNullAndUndefiend(selectedAngle)}
selected={selectedAngle === i}
hoveredColor={
colors.organs[hoveredAngle]
? colors.organs[hoveredAngle].rgb
: hoveredAngle % 2
? colors.globalOrganColors[1].rgb
: colors.globalOrganColors[0].rgb
}
selectedColor={
colors.organs[selectedAngle]
? colors.organs[selectedAngle].rgb
: selectedAngle % 2
? colors.globalOrganColors[1].rgb
: colors.globalOrganColors[0].rgb
}
hovered={hoveredAngle === i}
onMouseEnter={() => setHoveredAngle(i)}
onClick={() => {
selectedAngle === i ? setSelectedAngle(null) : setSelectedAngle(i)
}}
/>
})
}
{
isNotNullAndUndefiend(highligthed) && <div
style={{
position: 'absolute',
width: 72,
height: 70,
top: -6 + verticalScale(highligthed) - 20,
paddingTop: 10,
left: -40,
background: 'rgba(255, 255, 255, 0.8)'
}}
>
<HighlightedIndex
top={3}
color={
(isNotNullAndUndefiend(selectedAngle) &&
!isNotNullAndUndefiend(hoveredAngle))
? colors.organs[selectedAngle + 1]
? Color(colors.organs[selectedAngle + 1].rgb).toString()
: Color(colors.globalOrganColors[selectedAngle % 2 ? 0 : 1].rgb)
.toString()
: isNotNullAndUndefiend(hoveredAngle)
? colors.organs[hoveredAngle + 1]
? Color(colors.organs[hoveredAngle + 1].rgb).toString()
: Color(colors.globalOrganColors[hoveredAngle % 2 ? 0 : 1]
.rgb)
.toString()
: darkGreen
}
>
<HighlightedIndexContentTop>
Org.<HighlightedIndexValue>
{highligthed + 2}
</HighlightedIndexValue>
{/* {`Org.${highligthed + 2}`} */}
</HighlightedIndexContentTop>
</HighlightedIndex>
<HighlightedIndex
top={20}
color={
(isNotNullAndUndefiend(selectedAngle) && isNotNullAndUndefiend(hoveredAngle))
? Color('#84EEE6').toString()
: Color('#78D89D').toString()
}
>
<HighlightedIndexContent>
<HighlightedIndexValue>
{highligthed + 1}
</HighlightedIndexValue>
{/* {highligthed + 1} */}
</HighlightedIndexContent>
</HighlightedIndex>
<HighlightedIndex
top={20 + 20 - 7}
color={
(isNotNullAndUndefiend(selectedAngle) &&
!isNotNullAndUndefiend(hoveredAngle))
? colors.organs[selectedAngle]
? Color(colors.organs[selectedAngle].rgb).toString()
: Color(colors.globalOrganColors[selectedAngle % 2 ? 1 : 0]
.rgb)
.toString()
: isNotNullAndUndefiend(hoveredAngle)
? colors.organs[hoveredAngle]
? Color(colors.organs[hoveredAngle].rgb).toString()
: Color(colors.globalOrganColors[hoveredAngle % 2 ? 1 : 0]
.rgb)
.toString()
: Color('#78D89D').toString()
}
>
<HighlightedIndexContentBottom>
Org.<HighlightedIndexValue>
{highligthed + 1}
</HighlightedIndexValue>
{/* {`Org.${highligthed + 1}`} */}
</HighlightedIndexContentBottom>
</HighlightedIndex>
</div>
}
{
[selectedAngle, hoveredAngle]
.filter((d) => isNotNullAndUndefiend(d))
.map((d, i) => {
return <div
key={`interacted-angle-${i}`}
>
{
(isNotNullAndUndefiend(data.automated[d])) && (
<HoveredPoint
key={'main'}
top={verticalScale(d + 1) + barHeight - 4}
left={horizontalScale(
valueTransformFn(data.automated[d])
) + 37 - 7}
/>
)
}
{
(ifManualData && isNotNullAndUndefiend(data.manual[d])) && (
<HoveredPoint
red
key={'secondary'}
top={verticalScale(d + 1) + barHeight - 4}
left={horizontalScale(
valueTransformFn(data.manual[d])
) + 37 - 7}
/>
)
}
</div>
})
}
</InteractorContainer>
</Content>
})