Snippets Collections
// removes all duplicates of a key in a json array, in this case we create a new const that loops over a cities json array and checks for countries with the same name. it will return only the first instance of that country object where there are multiple of the same country

const countriesUnique = new Set(
  cities.map(city =>
    JSON.stringify({ country: city.country, emoji: city.emoji }),
  ),
)
const countries = [...countriesUnique].map(each => JSON.parse(each))
console.log(countries)
// use Fetch hook file
import { useState, useEffect } from "react";


const useFetchCities = (url) => { // need this url placeholder to put into where the fetch hook is being called


 const [cities, setCities] = useState([]);
 const [loading, setLoading] = useState(false);
 const [error, setError] = useState(null);



//fetch for local url => move later to a hook
 useEffect(() => {
      const citiesData = async(url) => {
        setLoading(true)
        try {
          const response = await fetch(url);
          if(!response.ok) return
          
          if(response.status === 200){
            const data = await response.json();
            setCities(data)
            
          }
        
        } catch (error) {
          setError(error)
          setLoading(true)
        }finally{
          setLoading(false)
        }
      }
      citiesData(url)
 
 }, [url]);


 return {cities, loading, error}
}


export default useFetchCities;






//import the hook into another file

// fetch hook for cities => see useFetchCties file
const {cities, loading, error} = useFetchCities(`${BASE_URL}/cities`);
star

Sun Feb 11 2024 04:02:25 GMT+0000 (Coordinated Universal Time)

#reacth #hook
star

Sun Feb 11 2024 00:23:42 GMT+0000 (Coordinated Universal Time)

#reacth #hook

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension