0
module.exports.fetchUser = () => {
    fetch('/api/user')
        .then((response) => response.json())
        .then((user) => {
            return user;
        });
}

I have a separate file called fetchApi.js that holds the function above. I'm trying to use it in the reactJS file below, but when I try to setState in the componentDidMount function, nothing is being set. It seems like the fetchUser function isn't returning the user object like I want it to. Am I using this wrong?

import React, {Component} from 'react';
import { fetchUser } from './fetchApi';

class Dashboard extends Component{
    constructor(props){
        super(props);

        this.state = {
            userData: {}
        }
    }
    componentDidMount(){
            this.setState({userData: fetchUser()});
    }
    render(){
        return(
            <div>
                <h1>
                    {this.state.userData.username ? this.state.userData.username : "Not Signed In"}
                </h1>               
                <h2>DASHBOARD</h2>
                <a href="/google">Login</a>
            </div>
        )
    }
}
benoit
  • 57
  • 2
  • 9

0 Answers0