Oops! Looks like there was an issue with the Json server - it seems there was

Hello everyone, I am currently attempting to post data to a JSON server using the POST method. Unfortunately, I am encountering errors. My application has buttons for actions such as follow and like. When a user clicks on the follow button, the number should increase and be saved to the JSON file. However, when a user clicks the button, I receive the following error message:

Note: I am utilizing a fake JSON server, you can find more information about it here

Error: Insert failed, duplicate id
    at Function.insert (C:\Users\jelly\AppData\Roaming\npm\node_modules\json-server\node_modules\lodash-id\src\index.js:49:18)
    // More lines of error messages here...

POST /statuses 500 13.873 ms - -

Below is the service code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Status } from '../model/statuses.model';
import { Comment } from '../model/comments.model';
@Injectable({
  providedIn: 'root'
})
export class UserService {
   status: Status[];
  constructor(private http: HttpClient) { }
  // Code continuation...

Here is the TypeScript file that accompanies the service:

import { Component, OnInit } from '@angular/core';
// Other import statements...

@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.scss']
})
export class UserProfileComponent implements OnInit {
  // Class properties and methods defined here...

  persistStatus(status) {
    this.userService.addStatus(status)
    .subscribe(data => {
      this.status = status;
    });

  }
}

JSON File Content:

{
  "statuses": [
    {
      "id": 1,
      // Additional fields of JSON data...
    }
  ]
}

Status Model definition:

export class Status {
    id: number;
    // Further model details...
}

I would appreciate any guidance or feedback on what might be causing issues in my code. Thank you!

Answer №1

According to the fake json-server documentation you're utilizing, it states that id values cannot be changed. Any id value provided in a PUT or PATCH request will be disregarded. The only time an id value is acknowledged is when set in a POST request, but only if it's not already in use.

Since you are attempting to update an existing status, you should make a put call instead of a post. Consider the following:

updateStatus(status: Status) { 
    return this.http.put(this.statusUrl + '/' + status.id, status); 
}

Utilize this method within the persistStatus function:

persistStatus(status) { 
    this.userService.updateStatus(status) 
    .subscribe(data => { 
        this.status = [status]; 
    }); 
}
>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm curious if there is a method to incorporate an array within a where: $or statement using sequelize?

I have an array of team IDs called teamsIdsSelected = ['1', '5', .., 'X'] In order to retrieve all the challenges associated with each team ID from the 'Challenge' table, I attempted the following: Utilizing this f ...

What causes the function endpoint to become unreachable when a throw is used?

One practical application of the never type in typescript occurs when a function has an endpoint that is never reached. However, I'm unsure why the throw statement specifically results in this unreachable endpoint. function error(message: string): ne ...

Implementing dual language codes for a single locale in internationalization (i18n) efforts

I am currently using i18n to display translations in English and Japanese. The default language is set to English with the code en, but I have recently discovered that my website is not utilizing the correct ISO language code for Japanese, which should be ...

Utilizing CucumberJs, Protractor, and TypeScript to Implement Dynamic Tags/Variables in .feature Files

Currently, I am facing a challenge where I have multiple environments with various features enabled. My goal is to streamline the CI/CD process by leveraging the available variables. Is it possible to automate this process by dynamically reading these va ...

Next.js threw a wrench in my plans when the HTML syntax was completely disrupted upon saving the index.js

I have encountered an issue in my VSCode environment while working on a next.js project. Whenever I attempt to save the index.js file, the HTML syntax crashes. I am at a loss on how to resolve this issue, so any assistance would be greatly appreciated. Tha ...

What is the method for displaying a cube map reflection on an object without revealing the cubemap in the backdrop?

Is it possible to display a cube map reflection on an object without showing the cubemap in the background? I am interested in achieving a reflection on a lever mechanism without the cubemap being visible in the background. Instead, I would like the backg ...

Customizing the starting number of rows per page in TablePagination from material-ui

As a newcomer to using materials, I am looking to customize the table pagination to show 'n' number of rows, for example 10, and remove the "Rows per page" dropdown. <TablePagination rowsPerPageOptions={[]} component="div" ...

What is the process for obtaining authorization to access user information?

I am facing a perplexing issue with my app settings. Despite setting everything up correctly, I am unable to authenticate my account on my website using the Javascript SDK. Whenever I try to console.log(me), I only receive public information. Upon furthe ...

Deactivate internationalization for a specific route in Next.js - i18n feature

I'm currently utilizing the deufakt i18n localization plugin to translate my webpage, but I have a specific requirement to disable localization for my /blog route. Essentially, what I want to achieve is: mypage.com/es/anotherRoute -> mypage.com/b ...

The Angular logout route appears to be neglected

I'm currently working on implementing a LogoutFunction, but I'm running into an issue where it's not being dispatched to my API (Spring Boot). The login functionality works perfectly fine. My goal is to pass an ID to the API and receive a su ...

React state is null and void

Experimenting with React and working on creating a basic chat application that will be linked to Firebase. I currently have one ChatApp container and one UserInput component. ChatApp -> import React from 'react'; import UserInput from &apos ...

Using Vue to make a REST API call in a JavaScript file

I have been trying to convert an Axios API call from a Vue page into a standalone module that can be reused multiple times in my app. Unfortunately, all my attempts so far have failed and I'm not sure if it's because I lack experience working wit ...

Pass authorization credentials within the header of an Angular 2 request

My goal is to authenticate a user by utilizing the btoa encryption login string in Angular 2 and sending it to the request headers. However, I have encountered an issue where the authorization key is being sent inside the request payload rather than the re ...

Tips on how to direct the attention to a text box within a unique dialog, ensuring that the blinking cursor highlights the input area

Is there a way to set autofocus on a textbox when opening a custom dialog box? I've tried using the autofocus attribute for the input field, but it doesn't seem to work for me. Can anyone provide guidance on how to achieve autofocus for a textfie ...

The Map<> type does not seem to offer autofill suggestions for union arrays

Can anyone explain why TypeScript isn't providing autofill suggestions for "foo" or "bar" when typing elements into an empty array in the code snippet below? const map: Map<string, ('foo' | 'bar')[]> = new Map([ ['hell ...

Table arranged by column orientation

I am facing a unique scenario where the backend data I receive is organized in a column-oriented format. Here is an example of how the data structure looks: [ { columnName: "ID", cells: [1, 2, 3, 4, 5] }, { columnName: "Name", cells: ["a", "b", "c ...

What is the best way to reposition an element to the end of its flexbox container?

I have a flexbox-container that contains multiple details-elements with flex-wrap behavior. My goal is to have a details-element move below the other elements within the container when it is opened. For example, I want it to go from this initial layout: ...

Angular ERROR: Trying to access rating property of an undefined value

I'm encountering an issue on a website where users can vote for their favorite animal. Whenever I try to select an animal to vote for, I receive an unclear error message that has been difficult to resolve even after searching online for a solution. A ...

Pass the pre-encoded value through Ajax

Is there a way to prevent AJAX from encoding an already encoded value when passing it through data? I'm facing this issue where my value gets further encoded. Any solutions? This is the AJAX code I'm using: $.ajax({ url: form.attr(" ...

Expanding your knowledge of AngularJS: utilizing ng-click to interact with elements

After a user clicks on an element in my app, I have some logic that runs. For example: html <h3 ng-click="showAlert('text')">this is text! (try to click and select)</h3> js $scope.showAlert = function(text) { console.log(' ...