Home > Enterprise >  React - How to reference reponse.data state?
React - How to reference reponse.data state?

Time:01-13

New to React, having trouble understanding how to reference object data from response.data. Consider the following code:

import React, {useRef, useState, useEffect} from "react";
import UserService from "../services/user.service";
import AuthService from "../services/auth.service";
   
export const getUser = () => {
    
    // Retrieve user info from locally stored JSON
    const currentUser = AuthService.getCurrentUser();
    const [user, setUser] = useState("");

    useEffect(() => {
        getUser();
    }, []);

    const getUser = () => {

        // Retrieve user info from DB using user id
        UserService.getUser(currentUser.id)
            .then(response => {
                setUser(response.data); // This is what I what I want to reference
                console.log(response.data);
            })
            .catch(e => {
                console.log(e);
            });
    };

    return (
        <div>
          {user.username}
        </div>
    );
};

I see the data properly returned in the console: {username: 'GlennQuagmire'}

And using debug tools in Webstorm, I see that user is being loaded with this value. But once we get to rendering {user.username}, nothing shows up. What am I doing wrong?

CodePudding user response:

Please look at the code, I used public API as a database but you can relate it to your code. I think you need to use response.json() and then set data. Also as you are setting the user as an object, the initial useState should be declared as an empty object const [user, setUser] = useState({});.

const {useEffect, useState} = React;

const App = () => {
    //const currentUser = AuthService.getCurrentUser();
    const [user, setUser] = useState("");

    useEffect(() => {
        getUser();
    }, []);

    const getUser = () => {
    // Retrieve user info from DB using user id
    fetch('https://api.agify.io/?name=Glenn Quagmire')
      .then((response) => response.json())
      .then((data) => {
        setUser(data);
        console.log(data)
      }).catch(e => {
        console.log(e);
      });
    };

    return (
        <div>
          {user.name}
        </div>
    );
};
ReactDOM.render(
  <App />,
  document.getElementById("root")
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>

CodePudding user response:

I found an answer, modeled in the return block:

    return (
        <div>
          {user && user.map((user, index) => (  
            <h1>{user.username}</h1>
          ))}
        </div>
    );
};

Seems like a roundabout way to get a single piece of data in there, but it works. If anyone has better suggestions, feel free to share.

  • Related