Skip to content

Instantly share code, notes, and snippets.

@richleach
Created April 21, 2021 23:35
Show Gist options
  • Save richleach/bc7ab23aab7bb461494539061e4e0afb to your computer and use it in GitHub Desktop.
Save richleach/bc7ab23aab7bb461494539061e4e0afb to your computer and use it in GitHub Desktop.
This file shows how to use the JSON Server, how to format GET requests inside of a useEffect call and how to format a DELETE request (it uses array.filter() to filter out the recently deleted note).) Also, a little bit of Material UI love in here too.
//this file calls the JSON Server, passes each returned note as a prop to the NoteCard component
import React, {useState} from 'react'
import { useEffect } from 'react'
import Grid from '@material-ui/core/Grid'
import { Container } from '@material-ui/core'
import NoteCard from '../components/NoteCard'
export default function Notes() {
const [notes, setNotes] = useState([])
useEffect(() => {
fetch('http://localhost:8000/notes')
.then(res => res.json())
.then(data => setNotes(data))
}, [])
const handleDelete = async (id) => {
await fetch('http://localhost:8000/notes/' + id, {
method: 'DELETE'
})
const newNotes = notes.filter(note => note.id != id)
setNotes(newNotes)
}
const rand = Math.floor(Math.random() * 10)+1
console.log(rand)
return (
<Container>
<Grid container spacing={3}>
{notes.map(note => (
<Grid item key={note.id} xs={12} md={6} lg={4}>
<NoteCard note={note} handleDelete={handleDelete} />
</Grid>
))}
</Grid>
</Container>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment