What is the best way to incorporate data from my API into my component?

App.js

import { Text, View, Button, FlatList } from 'react-native';
import { useEffect, useState } from 'react';
import * as React from 'react';

const API = 'https://randomuser.me/api/users/';

const User = (props) => (
  <View>
    <Text>Name: {props.fname} {props.lname}</Text>
    <Text>Country: {props.country}</Text>
  </View>
);
const renderUser = ({item}) => <User fname={item.results[0].name.first} lname={item.results[0].name.last} country={item.results[0].location.country}/>;

export default function App() {
  const [users, setUsers] = useState({});

  useEffect(() => {
  fetch(API)
  .then((response) => response.json())
  .then((json) => {setUsers(json);});}, []);

  return (
    <View>
      <Text>{}</Text>

      <Button title="add a user" onPress={() => {
        fetch(API)
        .then((response) => response.json())
        .then((json) => {setUsers(json);}), []}}
      />

      <FlatList data={users} renderItem={renderUser}/>

    </View>
  );
}

When I am trying to create a User component, the way I am referencing the first and last name as well as the country from json dataset is not working. I have tried using (item.results[0].name.first) but it still doesn't work. Can anyone help me figure out what I am doing wrong?

Answer №1

It appears that the API you have set is incorrect. After testing:

returns the expected results.

returns a 404 not found error.

UPDATE:

The response from the API is as follows:

{
  "results": [
    {
      "gender": "male",
      "name": {
        "title": "Mr",
        "first": "Harley",
        "last": "Green"
      },
      "location": {
        "street": {
          "number": 5662,
          "name": "Hoon Hay Road"
        }
      }
    }
  ]
}

You will need to update your code accordingly:

...
const renderUser = ({ item }) => {
  return (
    <>
      <User
        fname={item.name.first}
        lname={item.name.last}
        country={item.location.country}
      />
    </>
  );
};


export default function App() {
   return (
    <>
      <View>
        <Button
          title="add a user"
          onPress={() => {
            fetch(API)
              .then((response) => response.json())
              .then((json) => {
                setUsers(json);
              }),
              [];
          }}
        />

      
        <FlatList data={users.results} renderItem={renderUser} />
      </View>
    </>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Don't delay in fulfilling and resolving a promise as soon as possible

Currently, I am facing an issue with a downstream API call that is returning a Promise object instead of resolving it immediately. This is how I am making the downstream call: const response = testClient.getSession(sessionId); When I console.log(response ...

Experiencing receiving a null value for an XML-formatted string following the process of

I am new to android development and I am currently working on a project where I need to call a webservice that returns a JSON string as a response. This JSON string contains an XML formatted string as one of the entries. String jsoncontent=restTemplate.ge ...

Utilizing AJAX within a Rails application to dynamically alter a database field without the need for a traditional form

I am facing a scenario where I have implemented a table with certain rows structured as follows: <div class="row chord-table-row" id= <%= "chord-#{chord.id}" %>> <div class="small-1 columns"><%= chord.id %></div> < ...

Is there a way for me to detect when the progress bar finishes and execute a different function afterwards?

After clicking a button in my Javascript function, the button disappears and a progress bar is revealed. How do I trigger another function after a certain amount of time has passed? $('#go').click(function() { console.log("moveProgressBar"); ...

Passing variables to the ajax.done() function from within a loop - what you need to know

How can I pass a variable to the .done() method of an ajax call that is inside a loop? The code snippet below shows my initial attempt: <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </ ...

Exploring the mocking of document,hidden using Jasmine

Struggling to simulate document.hidden in an angular unit test, but facing issues. Tried the following solutions: spyOn(Document.prototype, <any>'hidden').and.returnValue(true); spyOn(Document, <any>'hidden').and.ret ...

The JSON data may be improperly formatted

My script is not functioning correctly, it returns about 20 undefined values before finally displaying the full_name: function retrieveUserInfo(phrase) { $.ajax({ url: 'get_staff_details.aspx?rand=' + Math.random(), type: &ap ...

Learn how to design a presentation template analog that delivers JSON instead of XML within the S&P platform

I currently have a presentation template in Search and Promote that returns XML responses. Now, I am looking to receive the response in JSON format. However, finding analogs of XML tags for JSON is proving to be quite challenging due to the complexity of ...

Invoke Selenium using JavaScript

Imagine I have this (fictional) JavaScript snippet: asynchronousOperation.addEventListener("completed", function (event) { if (event.property == "required value") tell Selenium we are good; else tell Selenium the test failed; }); ...

turning off next.js server side rendering in order to avoid potential window is undefined issues

I am currently managing a private NPM package that is utilized in my Next.js project, both of which are React and Typescript based. Recently, I integrated a graph feature into the NPM package and encountered an issue where any reference to window within t ...

Error 404 encountered while attempting to access dist/js/login in Node.JS bootstrap

I currently have a web application running on my local machine. Within an HTML file, I am referencing a script src as /node_modules/bootstrap/dist/js/bootstrap.js. I have configured a route in my Routes.js file to handle this request and serve the appropri ...

No definition found for state

Currently, I am facing an issue while trying to fetch data from an API, set it on my State, and display that state in a table. The problem arises because the render method is called first, causing my state to be undefined which leads to this specific issue ...

I am currently exploring next.js and working on creating a dedicated single post page within my project

I am currently working with Next.js and fetching some dummy data on the homepage. However, I am facing an issue when trying to create a separate page for each post obtained from the homepage. Although I have already coded it, I feel like there is room fo ...

Guide on serializing a Moose object and its associated nested Moose objects

Exploring a sophisticated method for serializing nested Moose objects within a Moose object. For example: package Asset; use Moose::Role; has 'value' => ( isa => 'Int' ); has 'owner' => ( isa => 'Person ...

"Exploring the functionalities of jquery .change() specifically in the

I have a jQuery change function set up to adjust the values of another select drop down whenever the user changes the month (to display the correct number of days). Everything works perfectly in most browsers, but Firefox seems to be giving me trouble :( ...

Is jQuery Autocomplete functioning properly on outdated browsers, but not on newer ones?

Here is the JSON data I have for my auto complete feature { "list" : [ { "genericIndicatorId" : 100, "isActive" : false, "maxValue" : null, "minValue" : null, "modificationDate" : 1283904000000, "monotone" : 1, "name":"Abbau", ...

Is there a way to dynamically incorporate line numbers into Google Code Prettify?

Having some trouble with formatting code and inserting/removing line numbers dynamically. The line numbers appear on the first page load, but disappear after clicking run. They don't show at all on my website. I want to allow users to click a button a ...

Transmitting a JSON object through an HTTP POST request on an Android device

This is not a duplicate. The provided link is outdated as "http client" has been removed in api23. I am attempting to send a JSON object: {"emailId":"example@example.com","address":"Naya bans","city":"Noida","pincode":"201301","account_number":"911235463 ...

Encountering Issues with Accessing Property

Upon trying to run my code, the console is displaying an error that I am unable to resolve. The error specifically states: "TypeError: Cannot read property 'author' of undefined." View the StackBlitz project here The error seems to be coming fr ...

The Battle of Brainpower: Smarty vs. JavaScript/AJAX

One question I have is: Is there a specific guideline or convention for determining when to use "Smarty templating" versus using JavaScript Ajax calls to generate content? I have the ability to generate content dynamically using Ajax/JavaScript calls. Whi ...