Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return Data From Other Component [React Native/React]

hope you guys have a great great day! 🙂

I want to ask something, i need to return some list data from API,

I have 3 files, one called getUser.js and the othe is User.js and OtherUser.js, i already fetch the data from API in getUser.js, and i need to access the data from getUser.js to populate User.js and OtherUser.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The Problem is, i can’t return the data in getUser.js

here’s my code in getUser.js

import React from "react";

export const getUser = async () => {
  await fetch("https://myapi.com")
    .then((response) => response.json())
    .then((res) => {
      return res;
    });
};

and when i console.log inside User.js and OtherUser.js, i got this

Promise {
  "_U": 0,
  "_V": 0,
  "_W": null,
  "_X": null,
}

the log

and here’s my code in User.js and OtherUser.js looks like:

import React, {useState} from 'react'
import { getUser } from './someplace/getUser'

export default function User() {
  useEffect(()=>{getDataFromUser()},[])

  const getDataFromUser = async() => {
   console.log(getUser())
  }
}

Did you guys know why? please help 🙂

>Solution :

Avoid using then chains, when using async-await. Refactor your getUser funciton to

export const getUser = async () => {
  const response = await fetch("https://myapi.com");
  const json = await response.json();
  return json;
};

Then in your User component

console.log(await getUser())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading