recoil#useSetRecoilState JavaScript Examples
The following examples show how to use
recoil#useSetRecoilState.
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: user.actions.js From react-recoil-jwt-authentication-example with MIT License | 6 votes |
function useUserActions () {
const baseUrl = `${process.env.REACT_APP_API_URL}/users`;
const fetchWrapper = useFetchWrapper();
const setAuth = useSetRecoilState(authAtom);
const setUsers = useSetRecoilState(usersAtom);
return {
login,
logout,
getAll
}
function login(username, password) {
return fetchWrapper.post(`${baseUrl}/authenticate`, { username, password })
.then(user => {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('user', JSON.stringify(user));
setAuth(user);
// get return url from location state or default to home page
const { from } = history.location.state || { from: { pathname: '/' } };
history.push(from);
});
}
function logout() {
// remove user from local storage, set auth state to null and redirect to login page
localStorage.removeItem('user');
setAuth(null);
history.push('/login');
}
function getAll() {
return fetchWrapper.get(baseUrl).then(setUsers);
}
}
Example #2
Source File: SkipLoginButton.js From discovery-mobile-ui with MIT License | 6 votes |
SkipLoginButton = () => {
const setAuthentication = useSetRecoilState(authenticationState);
if (showSkipLogin) {
return (
<Button
title="Skip Login"
onPress={() => setAuthentication(MOCK_AUTH)}
/>
);
}
return null;
}
Example #3
Source File: LocationPage.js From app-personium-trails with Apache License 2.0 | 6 votes |
export function LocationPage() {
const locationsLoadable = useRecoilValueLoadable(locationResults);
const setQuery = useSetRecoilState(locationQuery);
const { year, month, day } = useParams();
useEffect(() => {
// every time mounted, this make new object
setQuery({
year: Number(year),
month: Number(month),
day: Number(day),
});
}, [year, month, day]);
return (
<>
<LocationFilter year={year} month={month} day={day} />
{locationsLoadable.state === 'loading' ? (
<h1>Loading...</h1>
) : (
<Suspense fallback={<h1>loading</h1>}>
<Item.Group>
{locationsLoadable.contents.map(item => (
<LocationItem item={item} key={`location_item_${item.__id}`} />
))}
</Item.Group>
</Suspense>
)}
</>
);
}
Example #4
Source File: PersoniumAppWrapper.js From app-personium-trails with Apache License 2.0 | 6 votes |
function PersoniumCellURL() {
const setAuthInfo = useSetRecoilState($authInfo);
const [cellUrlInput, setCellUrlInput] = useState('https://');
const handleInput = useCallback(
e => {
setCellUrlInput(e.target.value);
},
[setCellUrlInput]
);
const handleSubmit = e => {
e.preventDefault();
// ToDo: validation
setAuthInfo({ cellUrl: cellUrlInput });
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="https://user.appdev.personium.io/"
onChange={handleInput}
/>
<button onSubmit={handleSubmit}>Submit</button>
</form>
</div>
);
}
Example #5
Source File: Canvas.js From recoil-paint with MIT License | 6 votes |
export default function Canvas() {
const ref = useRef();
const itemIds = useRecoilValue(itemIdsState);
const setLayoutState = useSetRecoilState(canvasLayoutState);
const onLayout = ({
nativeEvent: {
layout: { x, y, width, height }
}
}) => setLayoutState({ x, y, width, height });
return (
<View style={styles.root} ref={ref} onLayout={onLayout}>
<View style={styles.container}>
<CanvasBackground />
{itemIds.map(id => <CanvasItem key={`item-${id}`} id={id} />)}
<Selection />
</View>
</View>
);
}
Example #6
Source File: AddRectsButton.js From recoil-paint with MIT License | 6 votes |
export default function AddRectsButton() {
const [itemIds, setItemIds] = useRecoilState(itemIdsState);
const setSelectedIds = useSetRecoilState(selectedIdsState);
const handleClick = () => {
let space = 16;
let width = 100;
let height = 100;
let ids = [];
let start = itemIds.length;
for (let i=0; i<100; i++) {
let count = start + i;
let row = Math.floor(count / 5);
let col = count % 5;
let x = space * (col + 1) + width * col;
let y = space * (row + 1) + height * row;
let id = createNewShape({ x, y, width, height });
ids.push(id);
}
setItemIds([...itemIds, ...ids]);
setSelectedIds([]);
}
return (
<Button style={styles.root} onClick={handleClick}>
<Text style={styles.text}>Add 100 Rects</Text>
</Button>
);
}
Example #7
Source File: CanvasItem.js From recoil-paint with MIT License | 6 votes |
export default function CanvasItem({ id }) {
const [itemSnapshot, setItemSnapshot] = useState(null);
const itemState = useRecoilValue(itemWithId(id));
const setSelectedIds = useSetRecoilState(selectedIdsState);
const updatePosition = useUpdateItem();
const { onMouseDown } = useMove(({ status, origin, offset }) => {
if (status === 'start') {
setItemSnapshot(itemState);
}
if (status === 'moving' && itemSnapshot) {
updatePosition({
...itemSnapshot,
x: itemSnapshot.x + offset.x,
y: itemSnapshot.y + offset.y,
})
}
if (status === 'end') {
setItemSnapshot(null);
setSelectedIds(ids => {
if (origin.metaKey || origin.shiftKey) {
return [...ids, id];
}
return [id];
});
}
});
const Shape = createShape(itemState);
if (!Shape) {
return null;
}
return <Shape {...itemState} onMouseDown={onMouseDown} />;
}
Example #8
Source File: CanvasBackground.js From recoil-paint with MIT License | 6 votes |
export default function CanvasBackground(props) {
const setSelectedIds = useSetRecoilState(selectedIdsState);
const backgroundColor = useRecoilValue(backgroundColorState);
const handleClick = useCallback(() => {
setSelectedIds([]);
}, [setSelectedIds]);
return (
<View style={[StyleSheet.absoluteFill, { backgroundColor }]} onClick={handleClick} />
);
}
Example #9
Source File: NewItemButton.js From recoil-paint with MIT License | 5 votes |
export default function NewItemButton({ newShapeProps = {}, ...others }) {
const [newItem, setNewItem] = useState(null);
const setItemIds = useSetRecoilState(itemIdsState);
const setSelectedIds = useSetRecoilState(selectedIdsState);
const canvasLayout = useRecoilValue(canvasLayoutState);
const createNewItem = useNewItem();
const updatePosition = useUpdateItem();
const { onMouseDown } = useMove(({ status, origin, offset }) => {
if (status === 'start') {
setNewItem(null);
createNewItem({
...newShapeProps,
x: origin.clientX - canvasLayout.x,
y: origin.clientY - canvasLayout.y
})
.then(item => {
setNewItem(item);
setItemIds(items => [...items, item.id]);
setSelectedIds([]);
});
}
if (status === 'moving') {
if (newItem) {
updatePosition({
...newItem,
x: origin.clientX + offset.x - canvasLayout.x,
y: origin.clientY + offset.y - canvasLayout.y
})
}
}
if (status === 'end') {
if (newItem) {
setNewItem(null);
setSelectedIds([newItem.id]);
}
}
})
return <Button {...others} onMouseDown={onMouseDown} />;
}
Example #10
Source File: PlaygroundSettings.js From basis with MIT License | 5 votes |
function PlaygroundSettings() {
const theme = useTheme();
const [screens, setScreens] = useRecoilState(screensState);
const setComponentPreviewCounter = useSetRecoilState(
componentPreviewCounterState
);
return (
<Container bg="grey.t03" height="100%">
<div
css={{
display: "flex",
flexDirection: "column",
height: "100%",
overflowY: "auto",
}}
>
<Text textStyle="subtitle2" margin="4 6 0">
Screens
</Text>
<div css={{ flexGrow: 1, minHeight: 0 }}>
<List
lockVertically
values={screens}
onChange={({ oldIndex, newIndex }) => {
setComponentPreviewCounter(
(componentPreviewCounter) => componentPreviewCounter + 1
);
setScreens(arrayMove(screens, oldIndex, newIndex));
}}
renderList={({ children, props }) => (
<ul
css={{
boxSizing: "border-box",
margin: 0,
padding: `${theme.space[1]} ${theme.space[6]} 0`,
overflowY: "auto",
}}
{...props}
>
{children}
</ul>
)}
renderItem={({ isDragged, value, props }) => (
<PlaygroundScreenSettings
isDragged={isDragged}
id={value.id}
name={value.name}
width={value.width}
{...props}
/>
)}
/>
<PlaygroundNewScreenSettings />
</div>
</div>
</Container>
);
}
Example #11
Source File: Statistics.js From recoil-paint with MIT License | 5 votes |
export default function Statistics({ id, series, status, ...others }) {
const setItemState = useSetRecoilState(itemWithId(id));
const statisticsLoadable = useRecoilValueLoadable(statisticsQuery(id));
useEffect(() => {
if (statisticsLoadable.state === 'hasValue') {
setItemState(item => ({
...item,
...statisticsLoadable.contents,
status: 'loaded'
}));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [statisticsLoadable.state]);
let content;
if (status === 'loading') {
content = <ActivityIndicator size="large" />
} else {
content = (
<View style={styles.container}>
{series.map((serie, i) => (
<View
key={`serie-${i}`}
style={[
styles.bar,
{
height: serie * 100,
}
]}
/>
))}
</View>
)
}
return (
<Element
{...others}
style={styles.root}
>
{content}
</Element>
);
}
Example #12
Source File: Selection.js From recoil-paint with MIT License | 5 votes |
export default function Selection() {
const selectedIds = useRecoilValue(selectedIdsState);
const selection = useRecoilValue(selectionBoundingBox);
const setMovingItemIds = useSetRecoilState(movingItemIdsState);
const { onMouseDown } = useMoveItems(({ status }) => {
if (!selection) {
return null;
}
if (status === 'start') {
setMovingItemIds(selectedIds)
}
if (status === 'end') {
setMovingItemIds([])
}
})
if (!selection) {
return null;
}
const { x, y, width, height } = selection;
return (
<>
<View
style={[styles.selection, {
left: x,
top: y,
width,
height
}]}
onMouseDown={onMouseDown}
/>
<ResizeHandler />
</>
)
}
Example #13
Source File: location_stat.js From app-personium-trails with Apache License 2.0 | 5 votes |
export function useLocationACLSubscribe(__id, filepath) {
const setAclStatus = useSetRecoilState(locationACLStatusState(__id));
useEffect(() => {
function handleStatChange(stat) {
if ('acl' in stat && stat.acl.has('DAV::all')) {
setAclStatus(
stat.acl.get('DAV::all').has('DAV::read') ? 'public' : 'private'
);
} else {
setAclStatus('private');
}
}
statListener.subscribe(filepath, handleStatChange);
return function cleanup() {
statListener.unsubscribe(filepath, handleStatChange);
};
}, []);
const setLocationACLPrivate = useCallback(() => {
setAclStatus('loading');
setACL(filepath, authState.accessToken.access_token, []).then(() => {
statListener.fire(filepath, { acl: new Map([]) }); // Todo: use PROPFIND to get current stat.
});
}, [__id, filepath]);
const setLocationACLPublic = useCallback(() => {
setAclStatus('loading');
setACL(filepath, authState.accessToken.access_token, [
{ principal: 'DAV::all', privileges: ['DAV::read'] },
]).then(() => {
statListener.fire(filepath, {
acl: new Map([['DAV::all', new Set(['DAV::read'])]]), // Todo: use PROPFIND to get current stat.
});
});
}, [__id, filepath]);
const updateLocationACL = useCallback(() => {
statDirectory(filepath, authState.accessToken.access_token).then(res => {
if (!res.has(filepath)) {
console.log(`${filepath} is not found(PROPPATCH)`);
return;
}
statListener.fire(filepath, res.get(filepath));
});
});
return { updateLocationACL, setLocationACLPrivate, setLocationACLPublic };
}
Example #14
Source File: useCubeStore.js From minecraft-react with MIT License | 5 votes |
useSetCube = () => {
const setCubes = useSetRecoilState($cubes);
return (x, y, z) =>
setCubes(cubes => [...cubes, <Cube key={nanoid()} position={[x, y, z]} />]);
}
Example #15
Source File: PlaygroundScreen.js From basis with MIT License | 4 votes |
function PlaygroundScreen({ id, name, width, document, componentsLocation }) {
const componentPreviewCounter = useRecoilValue(componentPreviewCounterState);
const setScreens = useSetRecoilState(screensState);
const isInspectMode = useRecoilValue(isInspectModeState);
const [componentsAtMouse, setComponentsAtMouse] = useState({});
const setScreenWidth = (width) => {
setScreens((screens) => updateItemWithId(screens, id, { width }));
};
const setScreenDocument = (document) => {
setScreens((screens) => updateItemWithId(screens, id, { document }));
};
const [mousePosition, mouseMoveRef] = useMousePosition(
0, // enterDelay
0, // leaveDelay
10 // fps
);
const lastMousePosition = useRef();
const widthOnResizeStart = useRef();
useEffect(() => {
const { x, y } = mousePosition;
if (
x !== null &&
y !== null &&
(!lastMousePosition.current ||
lastMousePosition.current.x !== x ||
lastMousePosition.current.y !== y)
) {
const { scrollX, scrollY } = document.defaultView;
const componentsAtMouse = getComponentsAtPoint(
{
x: x - scrollX,
y: y - scrollY,
},
componentsLocation
);
setComponentsAtMouse(componentsAtMouse);
}
lastMousePosition.current = mousePosition;
}, [mousePosition, document, componentsLocation]);
useEffect(() => {
setComponentsAtMouse({});
}, [isInspectMode]);
return (
<Resizable
size={{ width }}
onResizeStart={() => {
widthOnResizeStart.current = width;
}}
onResize={(e, direction, ref, d) => {
setScreenWidth(widthOnResizeStart.current + d.width);
}}
minWidth={MIN_SCREEN_WIDTH}
maxWidth={MAX_SCREEN_WIDTH}
enable={{
top: false,
right: true,
bottom: false,
left: false,
topRight: false,
bottomRight: false,
bottomLeft: false,
topLeft: false,
}}
>
<div
css={{
display: "flex",
flexDirection: "column-reverse",
width,
height: "100%",
overflowY: "hidden",
}}
>
<Text color="grey.t75" margin="1 1 0">
<strong>{name}</strong> – {width}px
</Text>
<ComponentPreview
iframeTitle={`${name} screen preview`}
iframeStyle={{
flexGrow: 1,
backgroundColor: "white",
boxShadow:
"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",
}}
hasBodyMargin={false}
setDocument={setScreenDocument}
containerRef={isInspectMode ? mouseMoveRef : undefined}
highlightedComponents={componentsAtMouse}
onMouseLeave={() => {
setComponentsAtMouse({});
}}
key={
componentPreviewCounter /* See: https://github.com/ryanseddon/react-frame-component/issues/170 */
}
/>
</div>
</Resizable>
);
}
Example #16
Source File: PersoniumAppWrapper.js From app-personium-trails with Apache License 2.0 | 4 votes |
function PersoniumAuthentication() {
const isLocalMode = useRecoilValue($localMode);
const authInfo = useRecoilValue($authInfo);
const setLogin = useSetRecoilState(isLogin);
const setToken = useSetRecoilState(tokens);
const setBarInstalled = useSetRecoilState($barInstalled);
const [error, setError] = useState(null);
useEffect(() => {
let unmounted = false;
let autoRefreshID = -1;
const appUrlSplit = `${location.origin}${location.pathname}`.split('/');
const appCellUrl = isLocalMode
? 'https://app-personium-trails.appdev.personium.io/'
: `${appUrlSplit.slice(0, 3).join('/')}/`;
// const appCellUrl = 'https://app-personium-trails.appdev.personium.io/';
const targetCell = authInfo.cellUrl;
const handler = isLocalMode
? new PersoniumLoginROPC(
targetCell,
localStorage.getItem('USERNAME_FOR_DEVELOPMENT'),
localStorage.getItem('PASSWORD_FOR_DEVELOPMENT'),
'https://app-personium-trails.appdev.personium.io/'
)
: new PersoniumLoginHandler(targetCell);
// subscribe authentication state
localStorage.setItem(LS_LAST_LOGIN_CELL, targetCell);
console.log(appCellUrl, authInfo);
handler
.loginAsync(appCellUrl, authInfo)
.catch(res => {
// ToDo: change handling depending on situation.
console.log(JSON.stringify(res));
localStorage.removeItem(LS_LAST_LOGIN_CELL);
if (res.status === 404) {
setError({
message: 'Authentication failed',
body: `Cell not found: ${targetCell}`,
// ToDo: refactoring
bodyUrl: 'javascript: location.reload();',
});
} else {
setError({
message: 'Authentication failed',
body: 'Please login from your Home App',
bodyUrl: targetCell,
});
}
return Promise.reject(res);
})
.then(authState => {
// sined in successfully
console.log('logged in');
if (!unmounted) {
setToken(authState.accessToken);
}
// start refreshing access_token (per 3000 sec)
autoRefreshID = setInterval(() => handler.refreshAsync(), 3000 * 1000);
// check bar installed;
return authState
.updateBoxUrl() // ToDo: refactoring Promise chain
.then(() => {
setBarInstalled(true);
})
.catch(res => {
if (res.status === 403) {
console.log('bar not installed');
setBarInstalled(false);
}
});
})
.then(res => {
if (!unmounted) {
setLogin(true);
}
})
.catch(reason => {
console.log('error happened', reason);
});
return () => {
// unsubscribe
unmounted = true;
if (autoRefreshID != -1) {
clearInterval(autoRefreshID);
}
};
}, [authInfo, isLocalMode, setToken, setLogin, setError, setBarInstalled]);
return error ? (
<>
<h1>{error.message || 'Oops, you cannot sign in'}</h1>
<p>
<a href={error.bodyUrl}>{error.body || 'click'}</a>
</p>
</>
) : null;
}
Example #17
Source File: PersoniumAppWrapper.js From app-personium-trails with Apache License 2.0 | 4 votes |
export function PersoniumAppWrapper(props) {
const login = useRecoilValue(isLogin);
const barInstalled = useRecoilValue($barInstalled);
const [authInfo, setAuthInfo] = useRecoilState($authInfo);
const setLocalMode = useSetRecoilState($localMode);
const history = useHistory();
useEffect(() => {
console.log('mounted PersoniumAppWrapper');
// ToDo: Set initialState in RecoilRoot
const isLocalMode =
// false;
location.hostname === 'localhost' || location.hostname === '127.0.0.1';
setLocalMode(isLocalMode);
// Boot Script
const currentHash = location.hash.replace(/^#\/?/g, '#');
console.log({ currentHash });
let targetCell = null;
if (currentHash.startsWith('#cell')) {
// boot from Home App
const [target] = currentHash
.replace(/^#\/?/g, '')
.split('&')
.map(kv => kv.split('='))
.filter(([k]) => k === 'cell');
if (target) {
targetCell = target[1];
history.push('/');
} else {
throw `Something is wrong. Is hash wrong? ${currentHash}`;
}
} else {
// boot directly
// nextPath = currentHash;
const lastLoginCell = localStorage.getItem(LS_LAST_LOGIN_CELL);
targetCell = lastLoginCell ? lastLoginCell : null;
}
// oauth redirected
const url = new URL(location.href);
if (
url.searchParams.has('cellUrl') &&
url.searchParams.has('code') &&
url.searchParams.has('state')
) {
setAuthInfo({
cellUrl: url.searchParams.get('cellUrl'),
code: url.searchParams.get('code'),
state: url.searchParams.get('state'),
});
url.searchParams.delete('cellUrl');
url.searchParams.delete('code');
url.searchParams.delete('state');
window.history.replaceState({}, document.title, url.toString());
} else {
setAuthInfo(targetCell !== null ? { cellUrl: targetCell } : null);
}
// if (!targetCell) {
// // targetCell unknown
// setError({ message: 'Launch this app from your Home App again.' });
// return () => {};
// }
}, []);
if (login && barInstalled === true) return props.children;
return (
<div
style={{
display: 'flex',
alignItems: 'center',
height: '100vh',
flexDirection: 'column',
}}
>
<div style={{ flexGrow: 1 }} />
{(() => {
if (authInfo === null) return <PersoniumCellURL />;
// attempt to login
return (
<>
<PersoniumLoading />
{(() => {
if (!login) return <PersoniumAuthentication />;
if (!barInstalled) return <PersoniumBarInstaller />;
})()}
</>
);
})()}
<div style={{ flexGrow: 1 }} />
</div>
);
}
Example #18
Source File: PersoniumBarInstaller.js From app-personium-trails with Apache License 2.0 | 4 votes |
export function PersoniumBarInstaller() {
const [installStatus, setInstallStatus] = useRecoilState($installStatus);
const [installing, setInstalling] = useRecoilState($installing);
const setBarInstalled = useSetRecoilState($barInstalled);
const handleClick = useCallback(async () => {
let pollingStatusID = -1;
function updateInstallStatus(text) {
setInstallStatus(c => [...c, { time: Date.now(), text }]);
}
if (authState.accessToken.access_token === undefined) {
setInstalling(true);
return () => {
setInstalling(false);
};
}
if (installing) return;
setInstalling(true);
const { access_token } = authState.accessToken;
const res = await fetch(
'https://app-personium-trails.appdev.personium.io/__/app-personium-trails.bar'
);
if (res.status !== 200) {
throw new Error('Downloading Barfile is failed');
}
// download to memory
const buff = await res.arrayBuffer();
console.log(`Downloaded ${buff.byteLength} bytes`);
const boxURL = `${authState._targetCell}app-personium-trails`;
const sendRes = await fetch(boxURL, {
method: 'MKCOL',
body: buff,
headers: {
Authorization: `Bearer ${access_token}`,
'Content-Type': 'application/zip',
},
redirect: 'manual',
});
if (sendRes.status === 202) {
// Accepted
// const boxStatusURL = sendRes.headers.get('location');
pollingStatusID = setInterval(async () => {
const boxStatus = await fetch(boxURL, {
headers: {
Authorization: `Bearer ${access_token}`,
},
}).then(res => res.json());
const statusText =
boxStatus.box.status === 'ready'
? boxStatus.box.status
: `${boxStatus.box.status} ${boxStatus.box.progress}`;
updateInstallStatus(statusText);
if (boxStatus.box.status === 'ready') {
clearInterval(pollingStatusID);
// update boxURL
authState
.updateBoxUrl()
.then(() => {
console.log('bar installation is done');
setBarInstalled(true);
})
.catch(res => {
console.log('bar installation is failed', res);
setBarInstalled(false);
});
}
}, 500);
} else {
const err = await sendRes.json();
updateInstallStatus(err.message.value);
}
}, [installing, setInstallStatus, setInstalling, setBarInstalled]);
if (authState.accessToken === null) {
return <h1>Login First</h1>;
}
return (
<>
<h1>Install Application</h1>
<div>
<button onClick={handleClick} disabled={installing}>
Start Install
</button>
</div>
<div>
{installStatus.map(item => {
return <p key={`installation-status-${item.time}`}>{item.text}</p>;
})}
</div>
</>
);
}