kandi background
Explore Kits

json-server | full fake REST API | REST library

 by   typicode JavaScript Version: v0.17.0 License: MIT

 by   typicode JavaScript Version: v0.17.0 License: MIT

Download this library from

kandi X-RAY | json-server Summary

json-server is a JavaScript library typically used in Web Services, REST, Nodejs applications. json-server has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can install using 'npm i @ramonornela/json-server' or download it from GitHub, npm.
Get a full fake REST API with zero coding in less than 30 seconds (seriously). Created with <3 for front-end developers who need a quick back-end for prototyping and mocking.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • json-server has a medium active ecosystem.
  • It has 59172 star(s) with 5762 fork(s). There are 1030 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 535 open issues and 442 have been closed. On average issues are closed in 238 days. There are 76 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of json-server is v0.17.0
json-server Support
Best in #REST
Average in #REST
json-server Support
Best in #REST
Average in #REST

quality kandi Quality

  • json-server has 0 bugs and 0 code smells.
json-server Quality
Best in #REST
Average in #REST
json-server Quality
Best in #REST
Average in #REST

securitySecurity

  • json-server has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • json-server code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
json-server Security
Best in #REST
Average in #REST
json-server Security
Best in #REST
Average in #REST

license License

  • json-server is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
json-server License
Best in #REST
Average in #REST
json-server License
Best in #REST
Average in #REST

buildReuse

  • json-server releases are available to install and integrate.
  • Deployable package is available in npm.
  • Installation instructions, examples and code snippets are available.
  • json-server saves you 66 person hours of effort in developing the same functionality from scratch.
  • It has 172 lines of code, 0 functions and 36 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
json-server Reuse
Best in #REST
Average in #REST
json-server Reuse
Best in #REST
Average in #REST
Top functions reviewed by kandi - BETA

kandi has reviewed json-server and discovered the below as its top functions. This is intended to give you an instant insight into json-server implemented functionality, and help decide if they suit your requirements.

  • list resource names
    • Start the server
      • Creates a new app .
        • Update a resource .
          • Get a list of references from the collection .
            • get page object
              • Display a resource
                • Prints the list of resources
                  • Remove document related to the database
                    • Block to produce custom routes

                      Get all kandi verified functions for this library.

                      Get all kandi verified functions for this library.

                      json-server Key Features

                      Egghead.io free video tutorial - Creating demo APIs with json-server

                      JSONPlaceholder - Live running version

                      My JSON Server - no installation required, use your own data

                      :dog: husky - Git hooks made easy

                      :owl: lowdb - local JSON database

                      ✅ xv - a beautifully simple and capable test runner

                      Getting started

                      copy iconCopydownload iconDownload
                      npm install -g json-server
                      

                      Plural routes

                      copy iconCopydownload iconDownload
                      GET    /posts
                      GET    /posts/1
                      POST   /posts
                      PUT    /posts/1
                      PATCH  /posts/1
                      DELETE /posts/1
                      

                      Singular routes

                      copy iconCopydownload iconDownload
                      GET    /profile
                      POST   /profile
                      PUT    /profile
                      PATCH  /profile
                      

                      Filter

                      copy iconCopydownload iconDownload
                      GET /posts?title=json-server&amp;author=typicode
                      GET /posts?id=1&amp;id=2
                      GET /comments?author.name=typicode
                      

                      Paginate

                      copy iconCopydownload iconDownload
                      GET /posts?_page=7
                      GET /posts?_page=7&amp;_limit=20
                      

                      Sort

                      copy iconCopydownload iconDownload
                      GET /posts?_sort=views&amp;_order=asc
                      GET /posts/1/comments?_sort=votes&amp;_order=asc
                      

                      Slice

                      copy iconCopydownload iconDownload
                      GET /posts?_start=20&amp;_end=30
                      GET /posts/1/comments?_start=20&amp;_end=30
                      GET /posts/1/comments?_start=20&amp;_limit=10
                      

                      Operators

                      copy iconCopydownload iconDownload
                      GET /posts?views_gte=10&amp;views_lte=20
                      

                      Full-text search

                      copy iconCopydownload iconDownload
                      GET /posts?q=internet
                      

                      Relationships

                      copy iconCopydownload iconDownload
                      GET /posts?_embed=comments
                      GET /posts/1?_embed=comments
                      

                      Database

                      copy iconCopydownload iconDownload
                      GET /db
                      

                      Homepage

                      copy iconCopydownload iconDownload
                      GET /
                      

                      Static file server

                      copy iconCopydownload iconDownload
                      mkdir public
                      echo 'hello world' &gt; public/index.html
                      json-server db.json
                      

                      Alternative port

                      copy iconCopydownload iconDownload
                      $ json-server --watch db.json --port 3004
                      

                      Remote schema

                      copy iconCopydownload iconDownload
                      $ json-server http://example.com/file.json
                      $ json-server http://jsonplaceholder.typicode.com/db
                      

                      Generate random data

                      copy iconCopydownload iconDownload
                      // index.js
                      module.exports = () =&gt; {
                        const data = { users: [] }
                        // Create 1000 users
                        for (let i = 0; i &lt; 1000; i++) {
                          data.users.push({ id: i, name: `user${i}` })
                        }
                        return data
                      }
                      

                      Add custom routes

                      copy iconCopydownload iconDownload
                      {
                        "/api/*": "/$1",
                        "/:resource/:id/show": "/:resource/:id",
                        "/posts/:category": "/posts?category=:category",
                        "/articles\\?id=:id": "/posts/:id"
                      }
                      

                      Add middlewares

                      copy iconCopydownload iconDownload
                      // hello.js
                      module.exports = (req, res, next) =&gt; {
                        res.header('X-Hello', 'World')
                        next()
                      }
                      

                      CLI usage

                      copy iconCopydownload iconDownload
                      json-server [options] &lt;source&gt;
                      
                      Options:
                        --config, -c       Path to config file           [default: "json-server.json"]
                        --port, -p         Set port                                    [default: 3000]
                        --host, -H         Set host                             [default: "localhost"]
                        --watch, -w        Watch file(s)                                     [boolean]
                        --routes, -r       Path to routes file
                        --middlewares, -m  Paths to middleware files                           [array]
                        --static, -s       Set static files directory
                        --read-only, --ro  Allow only GET requests                           [boolean]
                        --no-cors, --nc    Disable Cross-Origin Resource Sharing             [boolean]
                        --no-gzip, --ng    Disable GZIP Content-Encoding                     [boolean]
                        --snapshots, -S    Set snapshots directory                      [default: "."]
                        --delay, -d        Add delay to responses (ms)
                        --id, -i           Set database id property (e.g. _id)         [default: "id"]
                        --foreignKeySuffix, --fks  Set foreign key suffix, (e.g. _id as in post_id)
                                                                                       [default: "Id"]
                        --quiet, -q        Suppress log messages from output                 [boolean]
                        --help, -h         Show help                                         [boolean]
                        --version, -v      Show version number                               [boolean]
                      
                      Examples:
                        json-server db.json
                        json-server file.js
                        json-server http://example.com/db.json
                      
                      https://github.com/typicode/json-server
                      

                      Module

                      copy iconCopydownload iconDownload
                      $ npm install json-server --save-dev
                      

                      my state keeps adding empty elements into its array

                      copy iconCopydownload iconDownload
                        const handleSubmit = (e) => {
                      ...
                              const indexFinder = persons.findIndex(person => person.name === newName)
                              newObj.id = persons[indexFinder].id
                              copy[indexFinder] = newObj
                              phoneService.update(persons[indexFinder].id, newObj)
                              .then(res => {
                                setErrorMessage(`Successfully updated ${newName}s number`)
                                setPersons(copy)})
                      ...
                        }
                      
                      copy[indexFinder[0].id] = newObj
                      
                        const handleSubmit = (e) => {
                      ...
                              const indexFinder = persons.findIndex(person => person.name === newName)
                              newObj.id = persons[indexFinder].id
                              copy[indexFinder] = newObj
                              phoneService.update(persons[indexFinder].id, newObj)
                              .then(res => {
                                setErrorMessage(`Successfully updated ${newName}s number`)
                                setPersons(copy)})
                      ...
                        }
                      
                      copy[indexFinder[0].id] = newObj
                      

                      trying to make &quot;npm run dev&quot; create 2 shell instances

                      copy iconCopydownload iconDownload
                      npm install -g concurrently
                      

                      json-server running but can't access its api due to 403

                      copy iconCopydownload iconDownload
                      "server": "json-server --watch db.json --port 3000"
                      

                      json-server returns HTTP 200 instead of 404 for query parameter filtered GET request, what is the best practice here &amp; how can 404 be returned?

                      copy iconCopydownload iconDownload
                      // In this example we simulate a server side error response
                      router.render = (req, res) => {
                        res.status(500).jsonp({
                          error: "error message here"
                        })
                      }
                      
                      // In this example we return 404 for no content
                      router.render = (req, res) => {
                        if (res.locals.data.posts.length < 1) {
                          res.status(404).jsonp({
                            error: "no posts"
                          });
                        } else {
                          res.jsonp(res.locals.data);
                        }
                      }
                      
                      // In this example we simulate a server side error response
                      router.render = (req, res) => {
                        res.status(500).jsonp({
                          error: "error message here"
                        })
                      }
                      
                      // In this example we return 404 for no content
                      router.render = (req, res) => {
                        if (res.locals.data.posts.length < 1) {
                          res.status(404).jsonp({
                            error: "no posts"
                          });
                        } else {
                          res.jsonp(res.locals.data);
                        }
                      }
                      

                      How to use json-server | Getting 404 for local db.json

                      copy iconCopydownload iconDownload
                      http://localhost:4000/posts
                      http://localhost:4000/comments
                      http://localhost:4000/profile
                      {
                          "posts": [{
                              "id": 1,
                              "title": "json-server",
                              "author": "typicode"
                          }],
                          "comments": [{
                              "id": 1,
                              "body": "some comment",
                              "postId": 1
                          }],
                          "profile": {
                              "name": "typicode"
                          }
                        }
                      http://localhost:4000/posts
                      http://localhost:4000/comments
                      http://localhost:4000/profile
                      {
                          "posts": [{
                              "id": 1,
                              "title": "json-server",
                              "author": "typicode"
                          }],
                          "comments": [{
                              "id": 1,
                              "body": "some comment",
                              "postId": 1
                          }],
                          "profile": {
                              "name": "typicode"
                          }
                        }

                      Downloading a json file (from json-server) as a txt or json or csv file, in an Angular app

                      copy iconCopydownload iconDownload
                      <a [href]="fileUrl" download="file.txt">DownloadFile</a>
                      
                      export class AppComponent implements OnInit {
                        name = 'Angular 5';
                        fileUrl;
                        constructor(private sanitizer: DomSanitizer) {  }
                        ngOnInit() {
                          const data = 'some text';
                          const blob = new Blob([data], { type: 'application/octet-stream' });
                      
                          this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
                        }
                      
                      }
                      
                      <a [href]="fileUrl" download="file.txt">DownloadFile</a>
                      
                      export class AppComponent implements OnInit {
                        name = 'Angular 5';
                        fileUrl;
                        constructor(private sanitizer: DomSanitizer) {  }
                        ngOnInit() {
                          const data = 'some text';
                          const blob = new Blob([data], { type: 'application/octet-stream' });
                      
                          this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
                        }
                      
                      }
                      

                      Is there a way to open a Visual Studio Code internal powershell window from NPM Script?

                      copy iconCopydownload iconDownload
                      {
                          "version": "2.0.0",
                          "tasks": 
                              [
                              {
                                  "label": "corePlugins",
                                  "type": "shell",
                                  "options": {
                                      "cwd": "${workspaceFolder}/frontend"
                                  },
                                  "command": "ng serve corePlugins"
                              },
                              {
                                  "label": "serve_conf_json",
                                  "type": "shell",
                                  "options": {
                                      "cwd": "${workspaceFolder}/frontend"
                                  },
                                  "command": "ng serve --configuration jsonserver"
                              },
                              {
                                  "label": "json-server",
                                  "group": "test",
                                  "type": "shell",
                                  "options": {
                                      "cwd": "${workspaceFolder}/json-server"
                                  },
                                  "command": "npm run start"
                              },
                              {
                                  "label": "startAllJson",
                                  "dependsOn": [
                                      "json-server",
                                      "corePlugins",
                                      "serve_conf_json",
                                  ]
                              }
                          ]
                      }
                      

                      Writing my own GeoJSON input component with a mapgox-gl interface

                      copy iconCopydownload iconDownload
                      import { useField } from 'react-final-form';
                      
                      export const MapInput = () => {
                         const { input, meta } = useField('geometry');
                         const { value, onChange } = input;
                         // do what you want with value and onChange
                      
                      export const MapInput = ({ source }) => {
                         const { input, meta } = useField(source);
                         const { value, onChange } = input;
                         // do what you want with value and onChange
                      
                      import { useField } from 'react-final-form';
                      
                      export const MapInput = () => {
                         const { input, meta } = useField('geometry');
                         const { value, onChange } = input;
                         // do what you want with value and onChange
                      
                      export const MapInput = ({ source }) => {
                         const { input, meta } = useField(source);
                         const { value, onChange } = input;
                         // do what you want with value and onChange
                      

                      multiple use state in react hooks

                      copy iconCopydownload iconDownload
                           function handleWatchedBtn(id) {
                          setMovies({
                            movies: movies.map((movie) => {
                              if (movie.id === id) {
                                return { movie, watched: !movie.watched };
                              }
                              return movie;
                            })
                          });
                        }
                      
                         function handleWatchedBtn(id) {
                          setMovies(
                             movies.map((movie) => {
                              if (movie.id === id) {
                                return { movie, watched: !movie.watched };
                              }
                              return movie;
                            })
                          );
                        }
                      
                           function handleWatchedChange(filter) {
                          setfilterByWatch({ filterByWatch: filter });
                        }
                      
                           function handleWatchedChange(value) {
                          setfilterByWatch(value);
                        }
                      
                           function handleWatchedBtn(id) {
                          setMovies({
                            movies: movies.map((movie) => {
                              if (movie.id === id) {
                                return { movie, watched: !movie.watched };
                              }
                              return movie;
                            })
                          });
                        }
                      
                         function handleWatchedBtn(id) {
                          setMovies(
                             movies.map((movie) => {
                              if (movie.id === id) {
                                return { movie, watched: !movie.watched };
                              }
                              return movie;
                            })
                          );
                        }
                      
                           function handleWatchedChange(filter) {
                          setfilterByWatch({ filterByWatch: filter });
                        }
                      
                           function handleWatchedChange(value) {
                          setfilterByWatch(value);
                        }
                      
                           function handleWatchedBtn(id) {
                          setMovies({
                            movies: movies.map((movie) => {
                              if (movie.id === id) {
                                return { movie, watched: !movie.watched };
                              }
                              return movie;
                            })
                          });
                        }
                      
                         function handleWatchedBtn(id) {
                          setMovies(
                             movies.map((movie) => {
                              if (movie.id === id) {
                                return { movie, watched: !movie.watched };
                              }
                              return movie;
                            })
                          );
                        }
                      
                           function handleWatchedChange(filter) {
                          setfilterByWatch({ filterByWatch: filter });
                        }
                      
                           function handleWatchedChange(value) {
                          setfilterByWatch(value);
                        }
                      
                           function handleWatchedBtn(id) {
                          setMovies({
                            movies: movies.map((movie) => {
                              if (movie.id === id) {
                                return { movie, watched: !movie.watched };
                              }
                              return movie;
                            })
                          });
                        }
                      
                         function handleWatchedBtn(id) {
                          setMovies(
                             movies.map((movie) => {
                              if (movie.id === id) {
                                return { movie, watched: !movie.watched };
                              }
                              return movie;
                            })
                          );
                        }
                      
                           function handleWatchedChange(filter) {
                          setfilterByWatch({ filterByWatch: filter });
                        }
                      
                           function handleWatchedChange(value) {
                          setfilterByWatch(value);
                        }
                      
                       function handleWatchedBtn(id) {
                          setMovies({
                            movies: movies.map((movie) => {
                              if (movie.id === id) {
                                return { movie, watched: !movie.watched };
                              }
                              return movie;
                            })
                          });
                        }
                      
                        function handleWatchedBtn(id) {
                          setMovies(() => movies.map((movie) => {
                              if (movie.id === id) {
                                return { movie, watched: !movie.watched };
                              }
                              return movie;
                            )
                          });
                        }
                      
                       function handleWatchedBtn(id) {
                          setMovies({
                            movies: movies.map((movie) => {
                              if (movie.id === id) {
                                return { movie, watched: !movie.watched };
                              }
                              return movie;
                            })
                          });
                        }
                      
                        function handleWatchedBtn(id) {
                          setMovies(() => movies.map((movie) => {
                              if (movie.id === id) {
                                return { movie, watched: !movie.watched };
                              }
                              return movie;
                            )
                          });
                        }
                      

                      VueJS access data attribute from another attribute

                      copy iconCopydownload iconDownload
                      export default {
                        components: {
                          VueGoodTable,
                        },
                        data() {
                          return {
                            // I need to access this unit at the formatFn function below
                            unit: 1000,
                           
                            rows: [],
                          };
                        },
                      computed:{
                         columns(){
                          return [
                              
                              {
                                label: "Amount",
                                field: "amount",
                                type: "number",
                                formatFn: (val) =>{
                                  let returnedVal = val / 100;
                                  returnedVal = returnedVal / this.unit;
                                  return returnedVal.toFixed(2);
                                },
                              },
                            ]
                      
                      
                       }
                      }
                        // methods to fetch the rows using a fake json-server api
                      };
                      

                      Community Discussions

                      Trending Discussions on json-server
                      • my state keeps adding empty elements into its array
                      • trying to make &quot;npm run dev&quot; create 2 shell instances
                      • json-server running but can't access its api due to 403
                      • I trying to json-server by npm install -g json-server, but everytime I get an error
                      • json-server returns HTTP 200 instead of 404 for query parameter filtered GET request, what is the best practice here &amp; how can 404 be returned?
                      • How to use json-server | Getting 404 for local db.json
                      • Can't install json-server
                      • Downloading a json file (from json-server) as a txt or json or csv file, in an Angular app
                      • In ' &quot;db&quot;: &quot;json-server -w db.json -p 3001&quot; ', what is '-w' in here means?
                      • Is there a way to run server with a session-persisted database connection in Django?
                      Trending Discussions on json-server

                      QUESTION

                      my state keeps adding empty elements into its array

                      Asked 2022-Apr-18 at 01:06

                      My setter, for SetPersons, seems to keep adding empty elements into its array for no apparent reason. I am trying to make my phone number list update instantaneously when I update a user's number but it sticks with the old number. Whenever I apply the logic to possibly make the number update instantly, it adds empty elements into my array instead and does not update instantly. Here is the code for each separate component:

                      App.js

                      import { useEffect, useState, useRef} from 'react'
                      import PersonForm from './components/PersonForm'
                      import Display from './components/Display'
                      import Filter from './components/Filter'
                      import phoneService from './services/information'
                      
                      const App = () => {
                        const [errorMessage, setErrorMessage] = useState('')
                        const [persons, setPersons] = useState('')
                        const [newName, setNewName] = useState('')
                        const [newNumber, setNewNumber] = useState('')
                        const [filter, setFilter] = useState('')
                        const [filterChecker, setFilterChecker] = useState('')
                        
                        useEffect(() => {
                          phoneService.getAll()
                          .then(people => setPersons(people))
                        }, [])
                      
                        const handleSubmit = (e) => {
                          e.preventDefault();
                          const copy = [...persons]
                          const foundNameOrNot = persons.some(el => el.name === newName)
                          const foundNumberOrNot = persons.some(el => el.number === newNumber)
                          const eachPersonsID = persons.map(person => person.id)
                          const newObj = {
                            name: newName,
                            number: newNumber,
                            id: Math.max(eachPersonsID) + 1
                          }
                          if (foundNameOrNot) {
                            if(window.confirm(`${newName} is added to phonebook, replace the old number with a new one.`)) {
                              const indexFinder = persons.filter(person => person.name === newName)
                              newObj.id = indexFinder[0].id
                              copy[indexFinder[0].id] = newObj
                              phoneService.update(indexFinder[0].id, newObj)
                              .then(res => {
                                setErrorMessage(`Successfully updated ${newName}s number`)
                                setPersons([copy])})
                              .catch(err => {
                                setErrorMessage(`Information on ${newName} has already been removed`)
                                setFilterChecker(filterChecker.filter(filter => filter !== newName))})
                            }
                          } else if (foundNumberOrNot) {
                            alert(`${newNumber} belongs to someone else`)
                          } else {
                            phoneService.create(newObj).then(res => setPersons([...persons, newObj]))
                          }
                        }
                      
                        const handleFilter = (e) => {
                          console.log(persons)
                          setFilter(e.target.value)
                          const allNames = persons.map(person => person.name)
                          setFilterChecker(allNames.filter(name => name.toLowerCase().indexOf(filter.toLowerCase()) !== -1))
                        }
                      
                        return (
                          <div>
                            <h1 className='error'>{errorMessage ? errorMessage : ''}</h1>
                            <h2>Phonebook</h2>
                            <Filter filter={filter} handleFilter={handleFilter}/>
                            <h2>add a new</h2>
                            <form onSubmit={handleSubmit}>
                              <PersonForm newName={newName} newNumber={newNumber} setNewName={setNewName} setNewNumber={setNewNumber}/>
                              <div>
                                <button type="submit">add</button>
                              </div>
                            </form>
                            <h2>Numbers</h2>
                            <Display filterChecker={filterChecker} persons={persons} setPersons={setPersons} setFilterChecker={setFilterChecker} errorMessage={errorMessage} setErrorMessage={setErrorMessage} />
                          </div>
                        )
                      }
                      
                      export default App
                      

                      Display.js

                      import phoneService from '../services/information'
                      import axios from 'axios'
                      import { useState } from 'react'
                      
                      const handleDelete = (i, persons, setPersons, name2, setFilterChecker, errorMessage, setErrorMessage) => {
                          if (window.confirm(`delete ${name2} ?`)) {
                              const newArrayOfPeople = persons.filter(person => person.name !== name2)
                              const newArrayOfNames = newArrayOfPeople.map(person => person.name)
                              setFilterChecker(newArrayOfNames)
                              setPersons(newArrayOfPeople)
                              phoneService.remove(persons[i].id)
                              setErrorMessage(`You have successfully deleted ${name2} from the list.`)
                              setTimeout(() => {
                                  setErrorMessage(null)
                              }, 5000)
                          }
                      }
                      
                      const Display = ({filterChecker, persons, setPersons, setFilterChecker, errorMessage, setErrorMessage}) => {
                          const copy = [...persons]
                          const findNumbers = []
                          const findNames = []
                          for (let j = 0; j < copy.length; j++) {
                              if (copy[j]?.name && !findNames.includes(copy[j]?.name)) {
                                  findNames.push(copy[j].name)
                              }
                          }
                          for (let i = 0; i < copy.length; i++) {
                              if (copy[i]?.number && !findNumbers.includes(copy[i]?.number)) {
                                  findNumbers.push(copy[i]?.number)
                              }
                          }
                        if (filterChecker) {
                          return (
                            findNames.map((name, i) => <div><nobr key={name}>{name} {findNumbers[i]}</nobr> <button onClick={() => handleDelete(i, persons, setPersons, name, setFilterChecker, errorMessage, setErrorMessage)}>delete</button></div>)
                            )
                        } else {
                          return ''
                        }
                      
                      }
                      
                      export default Display
                      

                      Filter.js

                      const Filter = ({filter, handleFilter}) => {
                          return <p>filter shown with <input value={filter} onChange={handleFilter}/></p>
                        }
                        
                        export default Filter
                      

                      PersonForm.js

                      import axios from 'axios';
                      import phoneService from '../services/information'
                      
                      const PersonForm = ({newName, newNumber, setNewName, setNewNumber}) => {
                      
                        return (
                          <div>
                            name: <input value={newName} onChange={(e) => setNewName(e.target.value)}/>
                            number: <input value={newNumber} onChange={(e) => setNewNumber(e.target.value)}/>
                          </div>
                        )
                      }
                      
                      export default PersonForm
                      

                      information.js

                      import axios from "axios"
                      const baseUrl = 'http://localhost:3002/numbers'
                      
                      const getAll = () => {
                        const request = axios.get(baseUrl)
                      
                        return request.then(response => response.data)
                      }
                      
                      const create = newObject => {
                        const request = axios.post(baseUrl, newObject)
                        return request.then(response => response.data)
                      }
                      
                      const update = (id, newObject) => {
                        const request = axios.put(`${baseUrl}/${id}`, newObject)
                        return request.then(response => response.data)
                      }
                      
                      const remove = (id) => {
                        const request = axios.delete(`${baseUrl}/${id}`)
                        return request.then(res => res.data)
                      }
                      
                      export default { getAll, create, update, remove, baseUrl }
                      

                      My json-server "db.json"

                      {
                        "numbers": [
                          {
                            "name": "uvaldo",
                            "number": "20",
                            "id": 6
                          },
                          {
                            "name": "uvaldo zumaya",
                            "number": "24",
                            "id": 7
                          },
                          {
                            "name": "uvaldo zumaya d",
                            "number": "26",
                            "id": 8
                          }
                        ]
                      }
                      

                      Whenever I try to update "uvaldo" phone number to 22, it just stays at 21 then throws errors, this picture is before I hit "add" to avoid the program crashing...

                      https://i.stack.imgur.com/CD2rh.png

                      ANSWER

                      Answered 2022-Apr-18 at 01:06

                      There are issues with the logic where you update persons.

                      Try this instead:

                        const handleSubmit = (e) => {
                      ...
                              const indexFinder = persons.findIndex(person => person.name === newName)
                              newObj.id = persons[indexFinder].id
                              copy[indexFinder] = newObj
                              phoneService.update(persons[indexFinder].id, newObj)
                              .then(res => {
                                setErrorMessage(`Successfully updated ${newName}s number`)
                                setPersons(copy)})
                      ...
                        }
                      

                      The reason why it was adding empty elements is that the index used to place newObj was greater than the size of the array:

                      copy[indexFinder[0].id] = newObj
                      

                      Also note that person.id does not necessarily mean that they are in that index of the array persons.

                      Source https://stackoverflow.com/questions/71906478

                      Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                      Vulnerabilities

                      No vulnerabilities reported

                      Install json-server

                      Create a db.json file with some data. Now if you go to http://localhost:3000/posts/1, you'll get.
                      If you make POST, PUT, PATCH or DELETE requests, changes will be automatically and safely saved to db.json using lowdb.
                      Your request body JSON should be object enclosed, just like the GET output. (for example {"name": "Foobar"})
                      Id values are not mutable. Any id value in the body of your PUT or PATCH request will be ignored. Only a value set in a POST request will be respected, but only if not already taken.
                      A POST, PUT or PATCH request should include a Content-Type: application/json header to use the JSON in the request body. Otherwise it will return a 2XX status code, but without changes being made to the data.

                      Support

                      For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

                      DOWNLOAD this Library from

                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                      over 430 million Knowledge Items
                      Find more libraries
                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                      Explore Kits

                      Save this library and start creating your kit

                      Explore Related Topics

                      Share this Page

                      share link
                      Consider Popular REST Libraries
                      Try Top Libraries by typicode
                      Compare REST Libraries with Highest Support
                      Compare REST Libraries with Highest Quality
                      Compare REST Libraries with Highest Security
                      Compare REST Libraries with Permissive License
                      Compare REST Libraries with Highest Reuse
                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                      over 430 million Knowledge Items
                      Find more libraries
                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                      Explore Kits

                      Save this library and start creating your kit

                      • © 2022 Open Weaver Inc.