1

I am new to React and need some help.

I am trying to create API functions on a separate file so that I can re-use it anytime.

I realized that I cannot use setState outside of component, so my approach was to have the function to return JSON object.

Api.js

export function getMemberInfo (loginInfo) 
{
    fetch('http:url/'+loginInfo[0].ID)
    .then(res => res.json())
    .then(json => {return json});
}
export default {getMemberInfo};

Members.js

import React, {Component} from 'react';
import {getMemberInfo} from './Api';

class Members extends Component {
    constructor(props) {
        super(props);
        this.state = {
            // Data from Login
            loginInfo:this.props.location.state,
            // Member Data
            memberInfo:[]
        };
    }
    componentWillMount() {
        console.log(getMemberInfo(this.state.loginInfo);
        this.setState({memberInfo: getMemberInfo(this.state.loginInfo)});
    }
};
export default Members;

When I see the result through console.log, I get undefined.

Is this the right approach?

Thank you for your help.

OHHO
  • 143
  • 2
  • 9

2 Answers2

2

First of all, you're trying to return a value inside then (asynchronous), you can either pass a callback (not recommended) or you leverage the power of async/await

export async function getMemberInfo (loginInfo) 
{
    const res = await fetch('http:url/'+loginInfo[0].ID);
    const json = await res.json();
    return json;
}
export default {getMemberInfo};

And in your components do the following:

import React, {Component} from 'react';
import {getMemberInfo} from './Api';

class Members extends Component {
    constructor(props) {
        super(props);
        this.state = {
            // Data from Login
            loginInfo:this.props.location.state,
            // Member Data
            memberInfo:[]
        };
    }
    async componentWillMount() {
        const memberInfo = await getMemberInfo(this.state.loginInfo);
        this.setState({ memberInfo });
    }
};
export default Members;

Ibraheem Al-Saady
  • 854
  • 3
  • 14
  • 30
0

You can solve this using async and await in your api function. The problem is that your fetch returns a promise, and your calling function does not return anything at all.

export function async getMemberInfo (loginInfo) 
{
    return await fetch('http:url/'+loginInfo[0].ID)
    .then(res => res.json())
    .then(json => {return json});
}
export default {getMemberInfo};
JSager
  • 1,420
  • 9
  • 18