简体   繁体   中英

JSX function in React not returning data?

I'm creating a simple GET API that collects data and spits it out as basic text in my front end. The API works and displays the data in console, but nothing is returned for the front end. Please help:

import React, { Component } from 'react';
import './Cards.css'

const data = {
    name: 'test',
    hobby: 'test'
}

function getUsers (data) { 
  fetch('http://localhost:3001/profile', {
    method: 'GET',
    headers: {
    'Content-Type': 'application/json',
    }
  })
  .then((response) => response.json())
  .then((data) => {
    console.log('Success:', data)
  })
  .then((data) => {
    return data.name
  })
  .catch((error) => {
    console.error('Error:', error)
  });
};


function Cards (data) {
  return (
    <div id='cards'>
      <div className="card-header" id='card-header'>
        Header
      </div>
      <div className="card-body" id='card-body'>
        <blockquote className="blockquote mb-0">
          <p>
            {getUsers(data)}
          </p>
          <footer className="blockquote-footer">Someone famous in <cite title="Source Title">Source Title</cite></footer>
        </blockquote>
      </div>
    </div>
  );
}


export default Cards;

The right way to address this is to fetch data from API (you can trigger the call through the useEffect hook), store the result in your component's state and then use this state value in your JSX.

import React, { useState, useEffect } from "react";
import "./Cards.css";

const data = {
  name: "test",
  hobby: "test"
};

function Cards(data) {
  const [name, setName] = useState("")

  useEffect(() => {
    getUsers()
  }, [getUsers])

  function getUsers(data) {
    fetch("http://localhost:3001/profile", {
      method: "GET",
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(response => response.json())
      .then(data => {
        console.log("Success:", data);
      })
      .then(data => {
        setName(data.name)
        return data.name;
      })
      .catch(error => {
        console.error("Error:", error);
      });
  }
  return (
    <div id="cards">
      <div className="card-header" id="card-header">
        Header
      </div>
      <div className="card-body" id="card-body">
        <blockquote className="blockquote mb-0">
          <p>{name}</p>
          <footer className="blockquote-footer">
            Someone famous in <cite title="Source Title">Source Title</cite>
          </footer>
        </blockquote>
      </div>
    </div>
  );
}

export default Cards;

i think that you should return the data if you are chaining another .then afterwards, it makes sense that the first then is console logging the data properly but the second gets no return.

 .then((data) => { console.log('Success:', data) [should be a 'return data' here?] }) .then((data) => { return data.name })

and also your function is async, so it should be inside a useEffect callback.

You can use useEffect and state as explained in comments, the code below should work:

import React, { Component, useEffect } from 'react';
import './Cards.css'

const data = {
    name: 'test',
    hobby: 'test'
}






function Cards (data) {
    const [ users, setUsers] = useEffect('')
    useEffect(() => {
        function getUsers (data) { 
            return fetch('http://localhost:3001/profile', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            }).then((response) => response.json())
            .catch((error) => {
                console.error('Error:', error)
            });
        };
        getUsers(data).then((data) => setUsers(data.name) )
    }, [])
    return (

        <div id='cards'>

            <div className="card-header" id='card-header'>
                Header
            </div>
            <div className="card-body" id='card-body'>
            <blockquote className="blockquote mb-0">
            <p>
            {users}
            </p>
            <footer className="blockquote-footer">Someone famous in <cite title="Source Title">Source Title</cite></footer>
            </blockquote>
            </div>
        </div>

    );}


export default Cards;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM