reactjs

How to render values onto screen?


I am trying to show the results from showUserInfo to show up on the page. How do I do this? I am wondering if I need to create something in the return portion of the code or if it's something else?

import React, { useState } from "react"; 
import axios from "axios"; 

export default function App() {

  const [counter, setCounter] = useState(0); 
  const [jsonData, setJsonData] = useState(""); // response 
  const [userInfos, setUserInfos] = useState([]);

  const getAPI = () => {
    axios.get('https://randomuser.me/api')
    .then(function ({ data }) {
      // handle success
      // console.log({ data });
      const stringifiedData = JSON.stringify(data); 
      setJsonData(stringifiedData); 
      showUserInfo(data); 
      console.log(data);
    })
    .catch(function (error) {
      // handle error
      console.log(error);
    })
  }

  const showUserInfo = ({ results }) => {
    const {0: { name }} = results;
    const {first, last} = name; 
    
    return (<div>`${first} {last}` </div>)
  }

  return (
    <div className="App">
      <button onClick={getAPI}>Get API</button>
      {userInfos}
    </div>
  );
}``` 

Solution

  • I think this is what you need.

    You can check here, I just made something similar, you can modify it with a few tweaks.

    Button to get User Info

    And here's the code that I'm testing:

    import "./styles.css";
    import { useState, useEffect } from "react";
    import axios from "axios";
    
    let url = "https://randomuser.me/api";
    
    export default function App() {
      const [counter, setCounter] = useState(0);
      const [userInfos, setUserInfos] = useState([]);
    
      const [jsonData, setJsonData] = useState("");
      const [userName, setUserName] = useState({});
    
      useEffect(() => {
        axios
          .get(url)
          .then((res) => {
            const stringifiedData = JSON.stringify(res.data);
            setJsonData(stringifiedData);
          })
          .catch((err) => console.log(err));
      });
    
      const updateUserInfo = () => {
        const data = JSON.parse(jsonData);
        const fullName = data.results[0].name;
        setUserName(fullName);
      };
    
      return (
        <div className="App">
          <button onClick={updateUserInfo}>Click to Update</button>
          <div className="user">
            {userName.first} {userName.last}
          </div>
        </div>
      );
    }
    

    We use useEffect to get the JSON that you need at first, then I setState for it with setJsonData like yours. But then in the updateUserInfo, you need to parse the jsonData back so we can use it normally because when we get through useEffect we've used stringify, so it's just a string, not an object like when we parsed complete, then it'll become easier, it'll have a structure like this, for example: {title: "Mr", first: "Kadir", last: "Balaban"}. And I create 1 more state called userName for testing it. You can try it.

    The {userName.first} {userName.last} at first render of React will have undefined value, so React understand it and will not render, so whenever we click the button, we set the fullName, then we call fullName.first and fullName.last, it'll update the state and render these value into the screen because now React understand that it's not undefined anymore.