On first Load useEffect hock Shows an error calling the api multiple time


I’m new to React.js
On the First Time load Code shows an error
when i comment this part {data.advice} and run it shows me html
it also calls API 2 times
it gives an Error on Reload. how to fix it?

import { Box, Button, Card, CardActions, CardContent, Container, Typography } from '@mui/material';
import axios from 'axios';
import React, { useEffect, useState } from 'react';

const Advice = () => {
    const [data, setData] = useState(null);
    const clicked = () => {
    const callAPI = () => {
            .then(respone => {
            .catch((error) => {
    useEffect(() => {
    }, [])
    return (
                <Typography variant='h2' sx={{ textAlign: "center" }}>Advice App</Typography>
                <Card sx={{ maxWidth: 500, margin: "10px auto", display: "block", textAlign: "center" }}>
                    {/* <CardMedia
                        sx={{ height: 140 }}
                        title="green iguana"
                    /> */}
                        <Typography gutterBottom variant="h5" component="div">
                            Advice of the Day
                        <Typography variant="body2" color="text.secondary">
                        <Button size="small" onClick={clicked}>Share</Button>
                        <Button size="small">Learn More</Button>

export default Advice;


Any Help will be Appreciated

>Solution :

As mentioned in the comments,

You are getting error because your code is trying to print advice property of data even before it is initialised. you can try below code to make sure it will print when data is present.

{data && data.advice}

The possible reason for sending two api calls might be because your app component is wrapped in <strict> tags. That means react is running in strict mode. This will call your effects twice and react will do that in dev mode only. So that is fine. Nothing to worry about. reference:
React 18 strict mode causing component to render twice

Leave a Reply Cancel reply