kandi background

json-server | full fake REST API with zero coding in less than 30 seconds | REST library

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.

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.
  • There were 1 major release(s) 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

quality kandi Quality

  • json-server has 0 bugs and 0 code smells.

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.

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.

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.
Top functions reviewed by kandi - BETA

Coming Soon for all Libraries!

Currently covering the most popular Java, JavaScript and Python libraries. See a SAMPLE HERE.
kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.

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

json-server Examples and Code Snippets

  • Getting started
  • Plural routes
  • Singular routes
  • Filter
  • Paginate
  • Sort
  • Slice
  • Operators
  • Full-text search
  • Relationships
  • Database
  • Homepage
  • Static file server
  • Alternative port
  • Remote schema
  • Generate random data
  • Add custom routes
  • Add middlewares
  • CLI usage
  • Module
  • 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
  • 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
  • Downloading a json file (from json-server) as a txt or json or csv file, in an Angular app
  • Is there a way to open a Visual Studio Code internal powershell window from NPM Script?
  • Writing my own GeoJSON input component with a mapgox-gl interface
  • multiple use state in react hooks
  • VueJS access data attribute from another attribute

Getting started

npm install -g json-server

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 .