Home > Software design >  Fetch function is called twice
Fetch function is called twice

Time:11-01

I was requesting data from a GraphQL server using fetch function in a file which I called fetching.js as shown below. However, fetchQuery() was getting called twice.

module.exports = {

    fetchQuery: function(query){
        console.log("fetchQuery started")

        return fetch('http://localhost:4000/', {
            method: 'POST',
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify({
                query: query
            })
        }).then(res => {
            return res.json()
        })
    },
 
    B: function(){
        console.log("This is function B. This is just a test.")
    }
 
}

This how I call fetchQuery(). I was trying to render the JSON data into a navigation bar in react. This is the code so far.

import React from 'react'
import '../App.css';
import {fetchQuery} from '../fetching'


function NavBar() {


    fetchQuery(`
        query{
            categories{
            name
            }
        }
    `).then(data => {

        const tab = document.createElement('a')
        tab.innerText = data.data.categories[0].name
        tab.href = "/"   tab.innerText

        const leftSide = document.getElementById('leftNavElements')

        tab.innerText = data.data.categories[0].name

        leftSide.append(tab)

    })

    return (
        <div className = "NavBar">
            
            <div className = "leftSide" id = "leftNav">

                <div className = "links" id="leftNavElements" >
                    <a href = "/">ALL</a>
                </div> 
            </div>

            <div className = "centerSide">
                Logo
            </div>

            <div className = "rightSide">
                Cart & Currency Change
            </div>

        </div>
    );
}

export default NavBar;

Please let me know how could I solve the bug

CodePudding user response:

Using native dom manipulation like document.createElement() is a bad practice in react.

Regardless, wrapping your fetchQuery in useEffect should fix your problem:

import { useEffect } from 'react'

useEffect(() => {

    fetchQuery(`
        query{
            categories{
            name
            }
        }
    `).then(data => {

        const tab = document.createElement('a')
        tab.innerText = data.data.categories[0].name
        tab.href = "/"   tab.innerText

        const leftSide = document.getElementById('leftNavElements')

        tab.innerText = data.data.categories[0].name

        leftSide.append(tab)

    })

, [])
  • Related