Extract a var from OnMount, like useState

Viewed 50

i'm trying to use a const that i created in onmount as {myip} in my code, i have no idea how to extract it from onmount

<script>
  import { page } from '$app/stores'
  import axios from 'axios'
  import { onMount } from 'svelte'

  onMount(async () => {
    const firstip = await axios.get(`https://geolocation-db.com/json/`)

    const finalip = await axios.get(`https://api.ipregistry.co/` + `${firstip.data.IPv4}` + `?key=6nn8zr4k2h34cwkw32`)

    if (!finalip.data.carrier.name) {
      const myip = finalip.data.location.city
      console.log(myip)
    } else {
      const myip = '7 km'
      console.log(myip)
    }
  })

  const { id } = $page.params

  console.log(id)
  const name = id.charAt(0).toUpperCase() + id.slice(1)
</script>

I would like to extract "myip" and use it outside onmount Thanks you

1 Answers

Simply declare it before as let and set it inside onMount

let myip

onMount(async () => {
    ...

    if (!finalip.data.carrier.name) {
      myip = finalip.data.location.city      
    } else {
      myip = '7 km'      
    }
})
Related