How can I get the ip of the device using React Native and Expo,
I'm trying this and all I see on the alert is [object promise].
I'm running the app on an emulator and on the browser..
import * as Network from 'expo-network';
alert(Network.getIpAddressAsync());
Network.getIpAddressAsync() returns a Promise, so you need to resolve it first.
import * as Network from 'expo-network';
const ipAlert = async () => {
const ip = await Network.getIpAddressAsync()
alert(ip);
};
ipAlert();
As it is written in the documentation, the method Network.getIpAddressAsync() returns a Promise that resolves to a String of the current IP address of the device's main network interface.
Due to this fact, you need to wait for the promise to finish as it is asynchronous.
You can do so by either attaching the await keyword before it, like this:
await Network.getIpAddressAsync();
or by chaining a then function afterwards, like so:
Network.getIpAddressAsync().then(function(address) {
//Your logic here
});
Related
I have an API Gateway resource which calls a Dynamodb post request to query a table. I'm trying to call the API within my React app using Axios. The API is working, returning the data as expected (console log) but I'm getting errors if I try to use #aws-sdk/util-dynamodb (unmarshall) to convert the api data.items response into JSON and use within React.
./node_modules/#aws-sdk/util-dynamodb/dist-es/convertToNative.js 45:14 Module parse failed: Unexpected token (45:14)
Is there a way to use 'unmarshall' within React? Something like this:
useEffect(() => {
const getGoal = async () => {
try {
const response = await api.get(apiUrl)
setGoal(unmarshall(response.data.Items))
This works if I use a Lambda service, but I'm try to see if I can reduce my code.
While I'm not sure on the issue you are getting with unmarshall function, I would suggest using the DynamoDB Document Client which will return your data already unmarshalled.
The DynamoDB Document client simplifies working with items by abstracting the notion of attribute values. This abstraction annotates native JavaScript types supplied as input parameters, and converts annotated response data to native JavaScript types.
<script>
import {onMount} from 'svelte';
import {session} from "$app/stores"
import {writable} from 'svelte/store';
const store = writable('some value');
let value = null
onMount(() => {
// this works
// return store.subscribe( (storeValue) => {value = storeValue}); // this works
// this throws an error:
// return session.subscribe( (sessionValue) => {value = sessionValue});
// Uncaught (in promise) Error: Function called outside component initialization
});
</script>
can someone please explain to me the problem with session.subscribe and why it keeps throwing?
if I move session.subscribe outside onMount it runs fine.
Note: this code is part of a SvelteKit Project, inside a Svelte component, not a SvelteKit page/route.
What goes wrong
It seems that you are actually experiencing intended behaviour. Under the documentation for $app/stores you will find this:
Stores are contextual — they are added to the context of your root component. This means that session and page are unique to each request on the server, rather than shared between multiple requests handled by the same server simultaneously, which is what makes it safe to include user-specific data in session.
Because of that, you must subscribe to the stores during component initialization (which happens automatically if you reference the store value, e.g. as $page, in a component) before you can use them.
When you were attempting this, you probably got a callstack that looks something like this:
Error: Function called outside component initialization
at get_current_component (index.mjs:953:15)
at getContext (index.mjs:989:12) <----------Here is the problem
at getStores (stores.js:19:17)
at Object.subscribe (stores.js:70:17)
at index.svelte:10:13
at run (index.mjs:18:12)
at Array.map (<anonymous>)
at index.mjs:1816:45
at flush (index.mjs:1075:17)
at init (index.mjs:1908:9)
We can see that Svelte attempts to call getContext when you subscribe to the session. Calling getContext outside of the component root is not allowed, which causes the subscription to fail.
I agree that this is quite unintuitive and I am not really sure why they implemented it this way.
Workaround
By the way, are you really sure you only want to subscribe to session on mount? What are you trying to do?
If you really only want to subscribe to session after component mount, you could use this workaround: Create your own store that updates whenever the session changes, then listen to that.
<script>
import { onMount } from "svelte";
import { session } from "$app/stores";
import { writable } from "svelte/store";
let mySession = writable($session);
$: $mySession = $session;
onMount(()=>{
mySession.subscribe(...whatever...);
})
</script>
I am trying to learn the simplest way to mock fetch with jest. I am trying to start with the official React docs recipe for fetch but it doesnt actually work without some modification.
My aim is to use Jest and (only) native React to wait for component rendering to complete with useEffect[].fetch() call before running assertions and testing initialisation worked.
I have imported the Data fetching recipe from official docs:
https://reactjs.org/docs/testing-recipes.html#data-fetching
into codesandbox here
https://codesandbox.io/s/jest-data-fetching-ov8og
Result: test fail
expect(received).toContain(expected) // indexOf
Expected substring: "123, Charming Avenue"
Received string: "loading..."
Possible cause?: I suspect its failing because global.fetch is not being used in the component which appears to be using real fetch hence is stuck "loading".
UPDATE
I have managed to make the test work through trial and error. Changed the call to fetch in the actual component to global.fetch() to match the test. This is not desirable for working code to refer to global prefix everywhere fetch is used and is also not in the example code.
e.g.
export default function User(props) {
const [user, setUser] = useState(null);
async function fetchUserData(id) {
// this doesnt point to the correct mock function
// const response = await fetch("/" + id);
// this fixes the test by pointing to the correct mock function
const response = await global.fetch("/" + id);
const json = await response.json();
setUser(json);
}
...
any help or advice much appreciated.
Is there any possibility to initialise Sentry twice on a page? Use case would be error tracking for parts of the app that are inserted as microfrontend.
So errors happen in this part of the app should be send to the teams own sentry project. I also wonder if there is any way filter the errors so only the ones that are relevant for the microfrontend are send and others are filtered out. Could we use reacts error boundaries for that?
Looks like there is a way to initialize something called Hub with a second dsn like this:
import {BrowserClient, Hub} from '#sentry/browser';
const client = new BrowserClient({
dsn: 'micorFrontEndSntryInstance'
});
const hub = new Hub(client)
this hub can passed to an ErrorBoundary wrapping your component.
In every componentDidCatch we can then send the error to the micro frontends sentry:
componentDidCatch(error, errorInfo) {
this.props.hub.run(currentHub => {
currentHub.withScope((scope) => {
scope.setExtras(errorInfo);
currentHub.captureException(error);
});
})
}
All the code is from this example implementation.
I would like server to emit series of events to client (React) after connection is established, Ive tried:
#socketio.on('connect')
def test_connect():
for i in range(10):
emit('my response', {'data': 'Connected ' + str(i)})
time_module.sleep(2)
but events shows in web browser console at the same time, like they arrived at the same moment, in react I use :
useEffect(() => {
const socket = socketIOClient(ENDPOINT);
socket.on('my response', function (data) {
console.log('my response: ', data.data);
})
})
There are two potential problems in your server code.
First of all, what is time_module in your example? I suspect that is a blocking sleep that you are doing. Instead, I suggest you sleep properly with socketio.sleep(2).
The second problem is that you are doing this in the connect event handler. The Socket.IO server waits until you return from the connect handler to decide if the client is accepted or rejected, so in general you do not want this handler to take a long time to run, because the connection isn't fully established until you return. I suggest you move this logic to a background function instead.
The following code addresses both issues:
def initial_events():
for i in range(10):
emit('my response', {'data': 'Connected ' + str(i)})
socketio.sleep(2)
#socketio.on('connect')
def test_connect():
socketio.start_background_task(initial_events)