React-Native wait for AsyncStorage.getItem() - react-native

I am facing problem exactly like what is mentioned in the link below:
https://github.com/facebook/react-native/issues/8589
Wish to load from AsyncStorage and set a few global variables. Because the rest of the pages depending on those variables.
If I use async await or then() I still can't stop the rest of the pages from rendering before the global variables are set.
I tried to make every component async, but unfortunately I can't get it working as well.
Mainly because of this line:
const _App = (props) => {
return (
<I18nextProvider i18n={i18next}>
<App />
</I18nextProvider>);
}
// registerComponent() can't accept anything that is Async
AppRegistry.registerComponent(appName, () => _App);

Try this
const _App = (props) => {
const [loaded, setLoaded] = useState(false)
useEffect(()=>{
const functionName = async () => {
await registerComponent()
setLoaded(true)
}
functionName()
},[])
if(!loaded) return <View><Text>Some Fancy loading stuff here</Text></View>
return (
<I18nextProvider i18n={i18next}>
<App />
</I18nextProvider>);
}

Related

Jest Testing onTouchStart/onTouchEnd

I've got a component that uses the onTouchStart and onTouchEnd and I can't figure out how to test it.
Here's a snack for the code, but the snippet is below:
export default function TouchComponent({
children,
onStart = doNothing,
onEnd = doNothing
}: TouchComponentProps): React.ReactElement {
return (
<View
onTouchStart={(e) => onStart()}
onTouchEnd={(e) => onEnd()}
>{children}</View>
);
}
const doNothing = () => {};
interface TouchComponentProps {
children?: React.ReactNode;
onStart?: () => void;
onEnd?: () => void;
}
Looking at the documentation, there aren't any methods listed for onTouchStart/onTouchEnd, but this method array seems to suggest that it has other methods that can be invoked, but it doesn't look like it works here because fireEvent["onTouchStart"](myComponent); fails with an error saying: TypeError: _reactNative.fireEvent.onTouchStart is not a function.
I've searched around but can't seem to find any documentation or other questions about testing onTouchStart and onTouchEnd, so how do I fire these events?
I figured this out almost immediately after asking this question. In my situation, I can invoke them like this:
import TouchComponent from "../TouchComponent ";
import { render, fireEvent } from "#testing-library/react-native";
it("Invokes onTouchStart and onTouchEnd", () => {
const { getByTestId } = render(
<TouchComponent
onStart={() => {
console.log("onTouchStart invoked");
}}
onEnd={() => {
console.log("onTouchEnd invoked");
}}
testID="my-component" />);
const myComponent = getByTestId("my-component");
// Passing empty {} data, but may need to supply for other use cases.
fireEvent(myComponent, "onTouchStart", {});
fireEvent(myComponent, "onTouchEnd", {};
});
// Console:
// console.log
// onTouchStart invoked
// console.log
// onTouchEnd invoked

Async custom hook from within useEffect

When kept in the component body, the following code works fine. Inside useEffect, it checks the asyncstorage and dispatches an action (the function is longer but other checks/dispatches in the function are of the same kind - check asyncstorage and if value exists, dispatch an action)
useEffect(() => {
const getSettings = async () => {
const aSet = await AsyncStorage.getItem('aSet');
if (aSet) {
dispatch(setASet(true));
}
};
getSettings();
}, [dispatch]);
I'm trying to move it to a custom hook but am having problems. The custom hook is:
const useGetUserSettings = () => {
const dispatch = useDispatch();
useEffect(() => {
const getSettings = async () => {
const aSet = await AsyncStorage.getItem('aSet');
if (aSet) {
dispatch(setASet(true));
}
};
getSettings();
}, [dispatch]);
};
export default useGetUserSettings;
Then in the component where I want to call the above, I do:
import useGetUserSettings from './hooks/useGetUserSettings';
...
const getUserSettings = useGetUserSettings();
...
useEffect(() => {
getUserSettings();
}, [getUserSettings])
It returns an error:
getUserSettings is not a function. (In 'getUserSettings()', 'getUserSettings' is undefined
I've been reading rules of hooks and browsing examples on the internet but I can get it working. I've got ESlint set up so it'd show if there were an invalid path to the hook.
Try the following.
useEffect(() => {
if (!getUserSettings) return;
getUserSettings();
}, [getUserSettings]);
The hook doesn't return anything, so it's not surprising that the return value is undefined ;)

React Native hooks - correct use of useEffect()?

I'm new to hooks and ran across this setup on SO and wanted to confirm that this is the correct pattern. I was getting the RN "unmounted component" leak warning message before and this seemed to solve it. I'm trying to mimic in some way compnentDidMount. This is part of a phone number verify sign up flow and onMount I want to just check for navigation and then fire off a side effect, set mounted true and then unmount correctly.
const SMSVerifyEnterPinScreen = ({ route, navigation }) => {
const [didMount, setDidMount] = useState(false)
const { phoneNumber } = route.params
useEffect(() => {
if(navigation) {
signInWithPhoneNumber(phoneNumber)
setDidMount(true)
}
return () => setDidMount(false)
}, [])
if (!didMount) { return null }
async function signInWithPhoneNumber(phoneNumber) {
const confirmation = await auth().signInWithPhoneNumber('+1'+phoneNumber)
...
}
return (
...
)
}
RN 0.62.2 with react-nav 5 - thanks!
Since signInWithPhoneNumber is a async function and will setState you will see warning it the component is unmounted before the response is available
In order to handle such scenarios you can keep a variable to keep track whether its mounted or not and then only set state is the mounted variable is true
However you do not need to return null if component has unmounted since that doesn't accomplish anything. The component is removed from view and will anyways not render anything.
Also you do not need to maintain this value in state, instead use a ref
const SMSVerifyEnterPinScreen = ({ route, navigation }) => {
const isMounted = useRef(true)
const { phoneNumber } = route.params
useEffect(() => {
if(navigation) {
signInWithPhoneNumber(phoneNumber)
}
return () => {isMounted.current = false;}
}, [])
async function signInWithPhoneNumber(phoneNumber) {
const confirmation = await auth().signInWithPhoneNumber('+1'+phoneNumber)
...
}
return (
...
)
}

React Redux Firebase Hooks: useSelector doesn't work

function FlashcardScreen() {
useFirestoreConnect('flashcards')
const projects = useSelector(state => {
state.firestore.data.flashcards
})
console.log(projects)
return(// some ui element)
}
My Question is when I console.log(state.firestore.data.flashcards) I get my data. But when I console.log(projects) I don't get it. Why? And does it have anything to do with redux-thunk?
In order to work, the arrow function in the selector should return some value e.g.
const projects = useSelector(state => {
return state.firestore.data.flashcards
})
Or simply remove the curly brackets
const projects = useSelector(state => state.firestore.data.flashcards)

how to handle failed silent auth error in auth0

I followed spa react quick start guide and it worked fine for more than a month. Recently i had this error and it is logged on auth0 as 'failed silent error' with no further information. I have been told that it is because of the browsers cookie updates and recommended to use new beta release of auth0-spa-js and change cache location to local storage. And it didn't work either.
The code is as follows:
auth_config.json:
{
"domain": "dev.........eu.auth0.com",
"clientId": "....eEKkQ.............",
"redirect_uri": "https://localhost:8080",
"audience": "https://.......herokuapp.com/v1/....",
"cacheLocation": "localstorage"
}
and
react-auth0-wrapper.js:
import React, { useState, useEffect, useContext } from "react";
import createAuth0Client from "#auth0/auth0-spa-js";
const DEFAULT_REDIRECT_CALLBACK = () =>
window.history.replaceState({}, document.title, window.location.pathname);
export const Auth0Context = React.createContext();
export const useAuth0 = () => useContext(Auth0Context);
export const Auth0Provider = ({
children,
onRedirectCallback = DEFAULT_REDIRECT_CALLBACK,
...initOptions
}) => {
const [isAuthenticated, setIsAuthenticated] = useState();
const [user, setUser] = useState();
const [auth0Client, setAuth0] = useState();
const [loading, setLoading] = useState(true);
const [popupOpen, setPopupOpen] = useState(false);
useEffect(() => {
const initAuth0 = async () => {
const auth0FromHook = await createAuth0Client(initOptions);
setAuth0(auth0FromHook);
if (window.location.search.includes("code=")) {
const { appState } = await auth0FromHook.handleRedirectCallback();
onRedirectCallback(appState);
}
const isAuthenticated = await auth0FromHook.isAuthenticated();
setIsAuthenticated(isAuthenticated);
if (isAuthenticated) {
const user = await auth0FromHook.getUser();
setUser(user);
}
setLoading(false);
};
initAuth0();
// eslint-disable-next-line
}, []);
const loginWithPopup = async (params = {}) => {
setPopupOpen(true);
try {
await auth0Client.loginWithPopup(params);
} catch (error) {
console.error(error);
} finally {
setPopupOpen(false);
}
const user = await auth0Client.getUser();
setUser(user);
setIsAuthenticated(true);
};
const handleRedirectCallback = async () => {
setLoading(true);
await auth0Client.handleRedirectCallback();
const user = await auth0Client.getUser();
setLoading(false);
setIsAuthenticated(true);
setUser(user);
};
return (
<Auth0Context.Provider
value={{
isAuthenticated,
user,
loading,
popupOpen,
loginWithPopup,
handleRedirectCallback,
getIdTokenClaims: (...p) => auth0Client.getIdTokenClaims(...p),
loginWithRedirect: (...p) => auth0Client.loginWithRedirect(...p),
getTokenSilently: (...p) => auth0Client.getTokenSilently(...p),
getTokenWithPopup: (...p) => auth0Client.getTokenWithPopup(...p),
logout: (...p) => auth0Client.logout(...p)
}}
>
{children}
</Auth0Context.Provider>
);
};
What is wrong with this code, any help appreciated. Or i can use a different method, i just followed the docs, it doesn't matter as long as it authenticates.
Thanks
I know this has been hanging around for a bit, but i was running into a similar issue.
As I understand it the createAuth0Client helper factory runs the getTokenSilently function by default as part of the set up to re-authenticate users every browser refresh. The problem i was having was that the call to getTokenSilently was erroring, meaning that auth0FromHook was never set and the auth0client never set in state. Because auth0client was undefined, it was then impossible to call loginwithredirect, which is the behaviour i wanted to achieve.
Basically i wanted it to auth silently, but if it failed, send to the log in screen, but that's impossible because the auth0client was undefined, resulting in a cannot call loginwithredirect of undefined error. It seems that (sadly) in the current stable version of the #auth0/auth0-spa-js library (1.6.5 at time of writing) there is no way to bypass getTokenSilently when initialising the client. However in the current beta (1.7.0-beta.5) (Here is a list of versions) they have exposed the Auth0Client class itself, so if you want to move to that version the code could be tweaked with something like....
initAuth0().catch( e => {
const newClient = new Auth0Client(initOptions);
setAuth(newClient);
})
and then in any protected components you can check the loading is finished and if isAuthenticated is still falsey, you should be able to redirect to login despite an error occurring during the getSilentToken.
== NON BETA OPTION
The alternative in the current api would be to perhaps set max_age to 0 or 1 in the initOptions, to force a re-login, and maybe setting prompt to "login" on the second attempt to initialize the authClient