React JS API Data Not Showing when using params

Viewed 27

I have a working API. When I console log the Data shows, but when I try to render it on the page it does work.

I am using params also. But I have added the API in full.

Please help me

import React, { useState, useEffect, } from "react";
import {useParams} from 'react-router-dom';

function ProductDetail(param) {

  const {id} = useParams();

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

  const [item, setItem] = useState({});
  const fetchItem = async () => {
    const fetchItem = await fetch(`https://fortnite-api.theapinetwork.com/item/get?id=087b55b4-b958-4dc3-8a4b-018fd54d12c4`
    );
    const item = await fetchItem.json();
    console.log(item.data);
}



  return (
    <div className="containter productsDetails">
      <h1>Product Detail
      </h1>
    </div>
  );
}

export default ProductDetail;

1 Answers

The below code should fix your issue. The API is returning data as a single object so when you try to render it you need to do it like - item['item'].anyPropertyInsideItemObject

Here is a result image - Result Screenshot

Hope that's how you wanted it work. You can modify it further however you want.

Full component code:

import React, { useState, useEffect, } from "react";
import {useParams} from 'react-router-dom';

function App() {

  const {id} = useParams();

  useEffect(async () => {
    const fetchItem = await fetch(`https://fortnite-api.theapinetwork.com/item/get?id=087b55b4-b958-4dc3-8a4b-018fd54d12c4`
    );
    const item = await fetchItem.json();
    setItem(item.data)
    console.log(item.data['item']);
    setIsLoading(false)
  }, []);

  const [item, setItem] = useState({});    
  const [loading, setIsLoading] = useState(true);    

  return (
    <div className="containter productsDetails">
      <h1>Product Detail
      </h1>
      {!loading && (
        <>
          <h3>Name : {item['item'].name}</h3>
          <h3>Description : {item['item'].description}</h3>
          <h3>Series : {item['item'].series}</h3>
          </>
      )}
    </div>
  );
}

export default App;

Related