Griffin Maree
Griffin Maree

Reputation: 61

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;

Upvotes: 1

Views: 738

Answers (3)

Fran&#231;ois Richard
Fran&#231;ois Richard

Reputation: 7055

You can use useEffectand 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;

Upvotes: 0

Arnaud Christ
Arnaud Christ

Reputation: 3551

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;

Upvotes: 1

RonBraha
RonBraha

Reputation: 36

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.

Upvotes: 0

Related Questions