Home > database >  How do i display data i have stored from a fetch request?
How do i display data i have stored from a fetch request?

Time:11-03

So i have made a fetch request and stored the data into a const. I am having trouble accessing the data to display it.

const [itemDetails, setItemDetails] = useState([]);

This is the structure of data stored in itemDetails and i cant figure out how to display it.

item:
customerCount: 0
itemCatName: "Furniture - Photos/Paintings/Prints"
itemCost: 21.96
itemDescription: "Removable and repositionable with no sticky residue. Perfect for nurseries, apartments, dorm rooms, and businesses. Wall decal stickers are mess-free, no paint, no glue/paste, no residue."
itemID: 6
itemImage: "/Images/I/51vJQpTLP7L._AC_.jpg"
itemName: "Golf Cart Seniors Isolated Peel and Stick Wall Decals "
unitsSold: 0

customerList: Array(197)
[0197]
0: {customerName: 'Joel Amess', email: '[email protected]', primaryPh: '491592807', secondaryPh: null, addressLine1: '51 Prince Street', …}
1: {customerName: 'Jack Schlink', email: '[email protected]', primaryPh: '0420194047', secondaryPh: null, addressLine1: '34 Round Drive', …}
2: {customerName: 'Jett Freeleagus', email: '[email protected]', primaryPh: '0489847578', secondaryPh: null, addressLine1: '48 Magnolia Drive', …}
3: {customerName: 'Brock Mills', email: '[email protected]', primaryPh: '0488806371', secondaryPh: null, addressLine1: '13 Taylor Street', …}
4: {customerName: 'Koby Wiedermann', email: '[email protected]', primaryPh: '0420029236', secondaryPh: null, addressLine1: '36 Reynolds Road', …}
5: {customerName: 'Eve Coane', email: '[email protected]', primaryPh: '0489973669', secondaryPh: null, addressLine1: '22 SWestern Australianston Street', …}

Any Help would be greatly appreciated

CodePudding user response:

You can map the itemDetails array and then return some HTML element for each item.

import { useEffect } from 'react'

const SomeComponent = () => {
    const [itemDetails, setItemDetails] = useState([]);

    useEffect(() => {
        // Do the fetching and setItemDetails here...
    });

    return (
        <div style={{ display: 'flex', flexDirection: 'column' }}>
            {itemDetails.map((item) => (
                <span>{item.customerName}</span>
            ))}
        </div>
    );
};

The map method creates an array from the items returned by the provided callback function. So here we are just directly creating an array of span elements that render inside the div.

CodePudding user response:

const { useEffect, useState } = React;

const App = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const URL = "https://jsonplaceholder.typicode.com/todos";
    fetch(URL)
      .then((response) => response.json())
      .then((json) => setUsers(json));
  }, []);

  return (
    <div>
      <h1> Test </h1>
      {users.map((user) => {
        return <div key={user.id}>{user.title} </div>;
      })}
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

You can useState for storing a data and use useEffect hook for calling API's. You can use fetch or Axios packages for that.

Example:

import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";

const App = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const URL = "https://jsonplaceholder.typicode.com/todos";
    fetch(URL)
      .then((response) => response.json())
      .then((json) => setUsers(json));
  }, []);

  return (
    <div>
      <h1> Test </h1>
      {users.map((user) => {
        return <div key={user.id}>{user.title} </div>;
      })}
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

Dependencies argument of useEffect is useEffect(callback, dependencies)

Let's explore side effects and runs:

Not provided: the side-effect runs after every rendering.

import { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Runs after EVERY rendering
  });  
}

An empty array []: the side-effect runs once after the initial rendering.

import { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Runs ONCE after initial rendering
  }, []);
}

Has props or state values [prop1, prop2, ..., state1, state2]: the side-effect runs only when any dependency value changes.

import { useEffect, useState } from 'react';

function MyComponent({ prop }) {
  const [state, setState] = useState('');
  useEffect(() => {
    // Runs ONCE after initial rendering
    // and after every rendering ONLY IF `prop` or `state` changes
  }, [prop, state]);
}
  • Related