Home > Net >  How to manage with data from fetch promise?
How to manage with data from fetch promise?

Time:10-19

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;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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.

  • Related