Program duplicates the same object with the same id

Issue

I’m following a tutorial on how to use React and Java in conjunction (using Ionic and Typescript) but I do not know much of JavaScript. It’s a simple CRUD where you can add, edit and remove clients of a list. Simple enough, yet when I either create a new client it both edits(or creates) an object but also duplicates its entry. I guess the problem is on the "save" button but I cant find the problem.

This is the specific editClient.tsx for the creation or edditing of an object

const { name, id } = useParams<{
    name: string;
    id: string;
}>();

const [client, setClient] = useState<any>({});/* this array will be called when we do a search*/

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

const history = useHistory();

const search = () => {
    if(id !== 'new') {
        let result = searchClientById(id);
        setClient(result);
    }
}

const save = () => {
    saveClient(client);
    history.push('/page/clients')
}

return (
    <IonPage>
        <IonHeader>
            <IonToolbar>
                <IonButtons slot="start">
                    <IonMenuButton />
                </IonButtons>
                <IonTitle>{name}</IonTitle>
            </IonToolbar>
        </IonHeader>

        <IonContent fullscreen>
            <IonHeader collapse="condense">
                <IonToolbar>
                    <IonTitle size="large"></IonTitle>
                </IonToolbar>
            </IonHeader>
            <IonCard>
                <IonTitle>{id === 'new' ? 'Set New Client' : 'Edit Client'}</IonTitle>
                <IonRow>
                    <IonCol>
                        <IonItem>
                            <IonLabel position="stacked">Name</IonLabel>
                            <IonInput onIonChange={e => client.firstname = e.detail.value} value={client.firstname}></IonInput>
                        </IonItem>
                    </IonCol>

                    <IonCol>
                        <IonItem>
                            <IonLabel position="stacked">Surname</IonLabel>
                            <IonInput onIonChange={e => client.surname = e.detail.value} value={client.surname}></IonInput>
                        </IonItem>
                    </IonCol>
                </IonRow>
                <IonRow>
                    <IonCol>
                        <IonItem>
                            <IonLabel position="stacked">Email</IonLabel>
                            <IonInput onIonChange={e => client.email = e.detail.value} value={client.email}></IonInput>
                        </IonItem>
                    </IonCol>

                    <IonCol>
                        <IonItem>
                            <IonLabel position="stacked">Adress</IonLabel>
                            <IonInput onIonChange={e => client.address = e.detail.value} value={client.address}></IonInput>
                        </IonItem>
                    </IonCol>
                    <IonCol>
                        <IonItem>
                            <IonLabel position="stacked">Phone</IonLabel>
                            <IonInput onIonChange={e => client.phone = e.detail.value} value={client.phone}></IonInput>
                        </IonItem>
                    </IonCol>
                </IonRow>
                <IonItem>
                    <IonButton onClick={save} color="primary" fill='solid' slot='end' size='default'>
                        <IonIcon icon={checkmark} />
                        Save Changes
                    </IonButton>
                </IonItem>
            </IonCard>
        </IonContent>
    </IonPage>
);

This is the saveClient function specific in the clientApi.tsx which is called in the previous code

export function saveClient(client:any) { 

    let clients = searchClient(); //array with clients
    
    if(client.id) {
        //edit - search by id & replace
        let index = clients.findIndex((c:any) => c.id == client.id);
        clients[index] = client;

    }else {
        //new - generates id & does a push to the array
        client.id = Math.round(Math.random()*10000);
        clients.push(client);

    }
    clients.push(client); //in that array we add the client we recive [].push(client)
    localStorage['clients'] = JSON.stringify(clients); //we transform it into a string
}

I tried a debugger in editClient.tsx’s save function but couldn’t get it to show me how the object is loaded. I reviewd it against the tutorial and, bar from the diference on language it’s on point. I think it might be a typo.

Solution

Your saveClient function’s logic is obviously faulty. you have a Clients.push(client) at the end of your function, so it would push anyways independent from the findIndex result. also findIndex would return -1 if it doesn’t find the result. here is the fixed version:

export function saveClient(client:any) { 

    let clients = searchClient(); //array with clients
    
    if(client.id) {
        //edit - search by id & replace
        let index = clients.findIndex((c:any) => c.id == client.id);
        if(index >= 0){
            clients[index] = client;
        }
        else{
            clients.push(client)
        }
    }else {
        //new - generates id & does a push to the array
        client.id = Math.round(Math.random()*10000);
        clients.push(client);

    }
    localStorage['clients'] = JSON.stringify(clients); //we transform it into a string
}

Answered By – AmirAli Saghaei

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published