Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
Fetch function is called twice

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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)

    })

, [])
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda