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

194
Visualizações
How to wait for fetch api values to return prior to exporting constant object

I have the following piece of code at the top level of my react component:

const myPriv = [];

export const myUserState = 
   {
     loggedIn: true,
     loggingIn: false,
     myPrivs: myPriv
   };

I am also performing the following fetch API call:

  const getPrivs = () => {
    const apiOptions = {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' }
    };

    return fetch(`${MY_ENDPOINT}/getMyPrivs`, apiOptions)
        .then(handleErrors)
        .then((response) => response.json())
        .then((json) => {
          myPriv.push(json[0].privs)
        })
        console.log('myUserState values: ', myUserState );
        .catch((error) => {
         console.log(error));
        }
 }

The issue I am having is that my myUserState.myPrivs array value is empty as it seems to be getting set/exported prior to my fetch api call to /getMyPrivs completing and setting myPriv array that is getting assigned to myUserState.myPrivs.

Unsure if I'm able to perform some form of ternary operation on the export to only perform this until myPriv array is populated?

Can anyone please assist on how to wait for myPriv.push(json[0].privs) to be set prior to myUserState export occurring inorder to ensure that myUserState.myPrivs array value(s) are avaialble?

about 4 years ago · Juan Pablo Isaza
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