1

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...

Endo Resu
  • 35
  • 1
  • 1
  • 4
  • Have you checked if your useEffect was triggered twice? Maybe console.log() inside useEffect, or did you see this only in the network tab? – Yevhen Kazmirchuk Apr 17 '22 at 19:15
  • @YevhenKazmirchuk honestly I wasn't even close to try console log inside useEffect, was only cheacking network tab, will try for sure, ty. Doubled request was before i tried to add useEffect as well, but I can't believe the fetch itself can be a bugged problem. – Endo Resu Apr 18 '22 at 01:51

0 Answers0