Home > Blockchain >  Proper way to fetch from another component - ReactJS
Proper way to fetch from another component - ReactJS

Time:11-21

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.

CodePudding user response:

If you want to separate the logic for requesting a URL into another helper function, you can create a custom hook.

// customHook.js

import { useEffect, useState } from 'react';

export function useLotteries() {
  const [lotteries, setLotteries] = useState(null);

  useEffect(() => {
    fetch('https://protected-sea-30988.herokuapp.com/https://www.lottoland.com/api/drawings;')
      .then(response => response.json())
      .then(json => setLotteries(json));
  }, []);

  return lotteries;
}

// Carousel.js

import { useLotteries } from "./customHook.js";

export const Carousel = () => {
  const [lotteries] = useLotteries();

  if (lotteries) {
    return; /* Your JSX here! (`lotteries` is now contains all the request responses) */
  } else {
    return <Loader />; // Or just null if you don't want to show a loading indicator when your data hasn't been received yet.
  }
};

CodePudding user response:

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)

}, [])
  • Related