-1

My react components are rendered in duplicate simultaneously and that creates problems for me during operations with Spring boot APIs, especially when I try to create an entity, and that generates constraint errors

import { useState, useEffect } from 'react';

export function useFetch(url, method, body, param, update) {

const [data, setData] = useState({});
const [isLoading, setLoading] = useState(true);
const [error, setError] = useState(false);


useEffect(() => {
    if (!url) return;

    setLoading(true)
    setError(false)
    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    myHeaders.append("Connection", "Keep-alive");

    var myInit = {
        method: (method ? method : "GET"),
        headers: myHeaders,
        mode: 'cors',
        cache: 'default',
        body: (body ? JSON.stringify(body) : null)
    };

    const allPath = "http://localhost:9000/streengeAPI" + url + (param ? 
 param : "");

    async function fetchData() {
        try {
            const response = await fetch(allPath, myInit);
            const data = await response.json();
            setData(data);
        } catch (err) {
            console.log(err);
            setError(true);
        } finally {
            setLoading(false);
        }
    }
    fetchData();

}, [url, method, body, param, update])
return { isLoading, data, error };
}

When I call this function in a component, this one is executed twice, so the spring api simultaneously receives the same request twice, and it creates constraint errors when creating a new entity.

java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'PR0019' for key 'PRIMARY'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117) ~[mysql-connector-java-8.0.29.jar:8.0.29]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.29.jar:8.0.29]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:916) ~[mysql-connector-java-8.0.29.jar:8.0.29]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1061) ~[mysql-connector-java-8.0.29.jar:8.0.29]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1009) ~[mysql-connector-java-8.0.29.jar:8.0.29]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1320) ~[mysql-connector-java-8.0.29.jar:8.0.29]
 at

com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:994) ~[mysql-connector-java-8.0.29.jar:8.0.29]

1 Answers1

1

i have found solution...! use this link : stackoverflow.com/a/65167384/19646557.

This is because of React Strict Mode code.

Remove -> React.StrictMode, from ReactDOM.render code.