Home > Software design >  How do I show the return values from a function?
How do I show the return values from a function?

Time:01-15

I am trying to show the return values for my getFullUserName function but nothing is displaying. I am wondering if I am missing something from the main return function? Everything displays in the console but just not on the screen.

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


export default function App() {
  const api = "https://randomuser.me/api?page="; 
  const [objectData, setObjectData] = useState([]);
  const [pageNumber, setPageNumber] = useState(1); 

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


  // ?page=2
  const getUser = () => {
    axios.get(`https://randomuser.me/api?page={pageNumber}`)
    .then(res => {
      const results = res.data.results; 
      const newObjectData = [
        ...objectData, ...results
      ]
      setObjectData(newObjectData);
      console.log(newObjectData);
      setPageNumber(() => pageNumber   1);
    })
    .catch(function (error) {
      // handle error
      console.log(error);
    })
  }


  const getFullUserName = (object) => {
    const first = object.name.first; 
    const last = object.name.last; 
    return `${first} ${last}` 

  }

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>Hi
      <h2>Start editing to see some magic happen!</h2>
      {
        objectData.map((object, idx) => {
          <p>{getFullUserName(object)}</p>
        })
      }
      <button onClick={getUser}>Grab another user </button>
    </div>
  );
}

CodePudding user response:

I needed to put in parenthesis for the return in the jsx in the getFullUserName.

CodePudding user response:

The issue is with the below (You are not returning anything)

{
    objectData.map((object, idx) => {
      <p>{getFullUserName(object)}</p>
    })
  }

You need to change it to

{objectData.map((object, idx) => (
    <p>{getFullUserName(object)}</p>
))}

Check the codesandbox for the full working code https://codesandbox.io/s/amazing-sea-v5xnz?file=/src/App.js

  •  Tags:  
  • Related