0

I have just started learning React and am struggling to create a component which calls and API and then presents the returned data on the page.

I have using state and am trying to update the state after calling my API which will then update the JSX code so the returned API data is presented on the browser.

Here is the code for my component

import { useParams } from "react-router";

const axios = require('axios');
const DEALS_API_URL = "";

const Deal = () => {
    let { deal_id } = useParams();
    const [deal, setDeal] = useState({});

    async function getDeal() {
        await axios.get(DEALS_API_URL + deal_id, {})
            .then(res => {
                setDeal(res.data);
            });
    }

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

    return (
        <div>
            <p>{deal.title}</p>
        </div>
    );
}

export default Deal;

Currently the page is loaded and the deal title is not displayed, how can I load the page and then when the state is updated after calling my API present the deal title on the browser

Luke Rayner
  • 391
  • 6
  • 20

1 Answers1

0

Since we are calling from an API, the data may not be available at first render. So we have to check when its available.

{deal ? (
  <p>{deal.title}</p>
) : <h1>Loading</h1>}
Nano Adam
  • 285
  • 1
  • 5
  • Hi thanks for the suggestion, I tried this and it doesnt seem to make a different I'm afraid – Luke Rayner Nov 09 '20 at 20:05
  • It won't work as the `deal` state is an object, so in if condition empty object is recognized as true and it will render the first part of condition always. In this case, you need to set `deal` to `null` or `undefined` initially. – Beso Kakulia Nov 09 '20 at 20:10
  • Or check the length of the object: `objectLength = Object.keys(exampleObject).length` and see if its greater than `0 or 1` (can't remember) – Nano Adam Nov 09 '20 at 20:21