0
votes

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

1
@JiaSH No of their solutions fix my problem - Luke Rayner
Are you sure res.data has a title property in it? can you hard code setDeal({title: 'some title'}) and check if UI updates. - Beso Kakulia
@BesoKakulia Im an idiot sorry, I was using an API which was similar and forgot to check if title existed. It works now - Luke Rayner

1 Answers

0
votes

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>}