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

171
Views
How to manage with data from fetch promise?

I am beginner in JS and React.

I have a problem:

import React from "react";

import JsonApi from "../../services/jsonApi";

const UserPage = () => {
  const jsonApi = new JsonApi(); //it is my class which has methods 
                                 //to manage with data(get,post,etc);

  const user = jsonApi.getUser(); //returns promise,but i need an object with data!
                                  //promise has such view:
                                  //[[Prototype]]: Promise
                                  //[[PromiseState]]: "fulfilled"
                                  //[[PromiseResult]]: Object  !!!!i need this data!!!!
  console.log(user); //Promise.

  /* i know that a i can do so:
     user.then((data) => console.log(data));

     but,using this way,i can only log!But i need an object with data!
  */


  return (
    <div className="app">
      <h1>{user.name}</h1> 
      <p>Here are info about users!</p>
    </div>
  );
};

export default UserPage;

I understand that i need to use await before const user = jsonApi.getUser();

but we can do that only inside async functions.

So,i tried to do that: const UserPage = async () => { }

but i had a mistake:

enter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

In order to perform side effects in react you should consider using useEffect hook. After the effect you need to store the data retrieved in react state by using the useState hook. In the end your code would look like below:

import React, { useState, useEffect } from "react";
import JsonApi from "../../services/jsonApi";

const UserPage = () => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const jsonApi = new JsonApi();
    jsonApi.getUser().then((user) => {
      setUser(user);
    });
  }, []);

  if (!user) return null;
  return (
    <div className="app">
      <h1>{user.name}</h1>
      <p>Here are info about users!</p>
    </div>
  );
};

export default UserPage;

Keep in mind that the user is not populated until you async getUser resolves, so you have to handle the case where user data are not yet present, either by rendering nothing (null) or by showing some loading state in between.

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