Home > Net >  Return Data From Other Component [React Native/React]
Return Data From Other Component [React Native/React]

Time:06-28

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

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 :)

CodePudding user response:

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())

CodePudding user response:

You are logging a Promise, that's why you're seeing this in your console.

When inside async function, if you want to get the result of the function, you should not use "then".

So you could do something like this:

const getUser = async () => {
  let response = await fetch("https://httpbin.org/get");
  return await response.json();
};

But, notice that if fetch fails, it may throw an exception. So I recommend using a try/catch block

Also notice that in this case, when you call getUser(), you will have to use "await" before calling the function to get the json response. For example:

let user = await getUser();

In case you want to run a async function inside the useEffect hook, try doing something like this:

React.useEffect(()=>{
  onOpen = async () => {            
    console.log(await getUser());
  }
  onOpen();
},[]);
  • Related