Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!