Search code examples
javascriptreactjsfetch-api

Proper way to fetch from another component - ReactJS


I have a component that fetches the data properly but I want to encapsulate it in a helper. I've tried many things but I'm stuck.

This is the component that works:

export const Carousel = () => {

const [ lotteries, setLotteries ] = useState({});
const [ isLoading, setisLoading ] = useState(true);

useEffect(() => {
    
    async function fetchAPI() {
        const url = 'https://protected-sea-30988.herokuapp.com/https://www.lottoland.com/api/drawings;'
        let response = await fetch(url)
        response = await response.json()
        
        setLotteries(response)
        setisLoading(false)
        }
    
        fetchAPI()
}, [])

return (

    <>
        {
            isLoading ? (
                <span>loading</span>
            ) : (

            <Slider >
                {
                Object.keys(lotteries).map((lottery, idx) => {
                    return (
                        <Slide 
                            key={ idx }
                            title={ lottery }
                            prize={ lotteries[lottery].next.jackpot }
                            day={ lotteries[lottery].next.date.day }
                        />
                    )
                })
                }
            </Slider>
        )}
    </>
);}

And this is the last thing I've tried so far. This is the component without the fetch

export const Carousel = () => {

const [ lotteries, setLotteries ] = useState({});
const [ isLoading, setIsLoading ] = useState(true);

useEffect(() => {
    
    getLotteries()
    setLotteries(response)
    setIsLoading(false)
      
}, [])

And this is where I tried to encapsulate the fetching.

export const getLotteries = async() => {

    const url = 'https://protected-sea-30988.herokuapp.com/https://www.lottoland.com/api/drawings;'
    let response = await fetch(url)
    response = await response.json()

    return response;
    
}

I'm a bit new to React, so any help would be much appreciated. Many thanks.


Solution

  • To get the fetched data from getLotteries helper you have to return a promise

    export const getLotteries = async() => {
    const url = 'https://protected-sea- 
     30988.herokuapp.com/https://www.lottoland.com/api/drawings;'
    let response = await fetch(url)
    return  response.json()
    

    }

    and call it as async/await

    useEffect(async() => {
    
    let response= await getLotteries()
    setLotteries(response)
    setIsLoading(false)
    
    }, [])