0

The code below get records from a web api. That's work, I get back the only record. But I don't understand why the WebApi is called 8 times.

Do you have an idea why ?

const Customer = () => {
    const [httpRequestDone, setHttpRequestDone] = useState(false);
    const [data, setData] = useState([]);

    if (!httpRequestDone) {
        axios({
            method: 'get',
            url: 'https://localhost:44368/api/Customer/AllCustomers',
        })
        .then(res => {
            console.log(res.data);
            setData(res.data);
            setHttpRequestDone(true);
        });   
    } 


    return (
        <div className="customer">
        <Navigation />       
        <ul>
            {data.map(item => (
                <li key={item.customerId}>
                    <div>{item.customerId}</div>
                    <div>{item.lastName}</div>
                </li>
            ))}
        </ul>

      </div>
    );
};

export default Customer;
TheBoubou
  • 19,487
  • 54
  • 148
  • 236

2 Answers2

1

If you want the fetch to only happen once then use useEffect hook.

const Customer = () => {
    const [data, setData] = useState([]);

    useEffect(function(){
    axios.get('https://localhost:44368/api/Customer/AllCustomers').then(function(res){
        setData(res.data);
        console.log(res.data);
    })
}, [])


    return (
        <div className="customer">
        <Navigation />       
        <ul>
            {data.map(item => (
                <li key={item.customerId}>
                    <div>{item.customerId}</div>
                    <div>{item.lastName}</div>
                </li>
            ))}
        </ul>

      </div>
    );
};

export default Customer;
SnaccOvenFlour
  • 158
  • 3
  • 14
1

Instead of using the useState hook to determine if you should make your axios call, maybe try the useEffect hook instead.

const Customer = () => {
    const [data, setData] = useState([]);

    useEffect(() => {
        axios({
            method: 'get',
            url: 'https://localhost:44368/api/Customer/AllCustomers',
        })
        .then(res => {
            setData(res.data);
        });   
    }, [])

    return (
        <div className="customer">
        <Navigation />       
        <ul>
            {data && data.map(item => (
                <li key={item.customerId}>
                    <div>{item.customerId}</div>
                    <div>{item.lastName}</div>
                </li>
            ))}
        </ul>

      </div>
    );
};

export default Customer;

This will only make your axios call once, when the component mounts.

larz
  • 5,724
  • 2
  • 11
  • 20