How to avoid double network requesting per one fetch in React 18?

55 Views Asked by At

Trying to make a memory card game by guide with React 18 and Pexels API I've meet some problem.

Trying to fetch data from API somehow my app send double network request per "mounting". Spent several hours trying to fix it with zero result. Also

useEffect(() => {
// some code
}, [])

can't solve my problem.

Code below

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import {App} from './App';

import './styles/index.scss';


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

App.js

import React from 'react';
import {Background} from './components/Background/Background';
import {useGetImages} from "./utils/hooks/useGetImages";

export const App = () => {
    const images = useGetImages();

    console.log({images})

    return (
        <>
            <Background/>
            <h1>Memory Game</h1>
        </>
    );
}

useGetImages.js // custom hook

import {useEffect, useState} from "react";
import {BASE_URL} from "../constants/constants";

const getRandomPage = () => Math.round(Math.random() * (60 - 1) +1);

export const useGetImages = () => {
    const [images, setImages] = useState([]);

    const buildUrl = () => {
        let url = new URL(BASE_URL);

        url.search = new URLSearchParams({
            query: 'nature',
            orientation: 'square',
            size: 'small',
            per_page: 2,
            page: getRandomPage(),
        });

        return url;
    };

    useEffect(() => {
        const fetchPics = () => {
            fetch(buildUrl(), {
                headers: {
                    Authorization: process.env.REACT_APP_AUTH_KEY,
                },
            })
                .then(data => data.json())
                .then(data => setImages(data.photos));
        };

        fetchPics();
    },[]);

    return images;
};

base url just in case

export const BASE_URL = 'https://api.pexels.com/v1/search';

P.S. component do not contain any logic just wierdo animations.

P.S.S. Can't share api key in terms of Pexels rules and laws.

Help me pls...

0

There are 0 best solutions below