'How to fetch data from a specific user
So my question is, how do i link every Item to the right users and how to fetch the data right? I want ever user in my json db to have a multiple goalItems. As every User has a unique Id, for fetching the data only from the specific user i tried by using "fetch ('http://localhost:5000/goalItems? usersId={usersId}')" but it didn't work.
Down Below you can find the DB.json file, the FULLGOAl Component, thats where the data is fetched and the GoalItem-Component
DB.JSON
{
"users": [
{
"id": "1",
"name": "Jules",
"logindate": ""
}
],
"goalItems": [
{
"id": 1,
"usersId": "",
"text": "XY",
"completed": false,
"completedDate": "18.2.2022, 14:18:24",
"note": "XY"
},
{
"id": 2,
"usersId": "",
"text": "ZY",
"completed": true,
"completedDate": "17.2.2022, 16:40:56",
"note": "ZY"
}
]
}
FullGoal this is where the data is fetched
import React, {useState, useEffect} from 'react'
import GoalItems from './GoalItems'
import DropDownMenu from "./DropDownMenu"
import CompletedLevelPopUp from './CompletedLevelPopUp'
import {useParams} from "react-router-dom";
import levelBatch1 from "./Icons/LevelBatch1.svg"
import levelBatch2 from "./Icons/LevelBatch2.svg"
const levelOption ={
1:
["A",
"B",
"C"
],
2: ["D",
"E",
"F"
}
const FullGoal = ({setNextLevelOpen}) => {
const [editLevel, setEditLevel] = useState(true)
const [goalItems, setGoalItems] = useState ([])
const [completedDate, setCompletedDate] = useState (false)
useEffect (() => {
var completedItems = []
goalItems.forEach(g => g.completed === true | completedItems.push(g.completed))
console.log(completedItems)
if(completedItems.length > 0){
function allCompl(element) {
return element === true
}
completedItems.every(allCompl) ? setOpenPopup (true) : setOpenPopup(false)
}
}, [goalItems])
useEffect (() => {
const getGoalItems = async () => {
const goalItemsFromServer = await fetchGoalItems()
setGoalItems(goalItemsFromServer)
}
getGoalItems()
}, [])
// Fetch Goals
const fetchGoalItems = async () => {
const res = await fetch ('http://localhost:5000/goalItems? usersId={usersId}')
const data = await res.json()
return data
}
//Fetch Goal
const fetchGoal = async (id) => {
const res = await fetch (`http://localhost:5000/goalItems/${id}`)
const data = await res.json()
return data
}
const addGoal = async (goal, id) =>{
const res = await fetch (`http://localhost:5000/goalItems`, {
method:'POST',
headers:{
'Content-type': 'application/json'
},
body: JSON.stringify(goal)
})
const data= await res.json ()
setGoalItems([...goalItems, data])
}
const toggleChecked = async (id) =>{
const goalToToggle = await fetchGoal(id)
const updatedGoal = {...(goalToToggle), completed : !goalToToggle.completed , completedDate : new Date().toLocaleString() + ""}
const res = await fetch (`http://localhost:5000/goalItems/${id}`, {
method: 'PUT',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(updatedGoal)
})
const data = await res.json()
setGoalItems(goalItems.map((goal)=> goal.id === id
? {...(goal), completed: data.completed, completedDate:data.completedDate} : goal
))}
const deleteFromJson = async (id) => {
await fetch(`http://localhost:5000/goalItems/${id}`, {
method: 'DELETE'
})
setGoalItems(goalItems.filter((goal) => goal.id !== id))
}
const noteSaveJson = async (id) => {
goalItems.forEach( async e=> {
const res = await fetch (`http://localhost:5000/goalItems/${e.id}`, {
method: 'PUT',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(e)
})
})
}
useEffect (noteSaveJson, [goalItems])
return (
<div className="fullGoal">
<div className="dropDownMenuBox">
{editLevel && <DropDownMenu options={levelOption[level] || [] } onAdd={addGoal}/> }
</div>
<div className="goalItemsBox">
<GoalItems id="goalItemBox"
goalItems={goalItems}
completedDate={completedDate}
onChange={v => {
setGoalItems(v)
}}
onToggle={toggleChecked}
editLevel={editLevel}
onDelete={deleteFromJson} />
</div>
</div>
)
}
export default FullGoal
** THIS IS THE GOALITEM COMPONENT **
import React, {useState} from 'react'
import {TiDelete} from 'react-icons/ti'
import {AiFillCheckCircle} from 'react-icons/ai'
import {CgNotes} from 'react-icons/cg'
const GoalItems = ({goalItems, onToggle, editLevel, onChange, onDelete, completedDate}) => {
const [noteOpen, setNoteOpen] = useState (false)
return (
<>
{goalItems.map((goal, index)=>(
<>
<div key={goal.id} className= {`singleGoalItem ${goal.completed ? 'completed' : ''}`} onDoubleClick={()=>onToggle(goal.id)}>
<h3 id="goalTitle">{goal.text}</h3>
<CgNotes id="goalIconNote" onClick={()=> setNoteOpen(!noteOpen)}/>
{editLevel && <TiDelete id="goalIconDelete" onClick={()=> {
onDelete(goal.id)
goalItems.splice(index, 1)
onChange([...goalItems])
}}/>}
{goal.completed ? <AiFillCheckCircle id="goalIconCheck"/> : ''}
</div>
<div>
{noteOpen? <div className="noteBox">
<textarea title="Note"
type ="text"
value= {goal.note}
onChange= {(e)=> {
goalItems[index].note= e.target.value
onChange([...goalItems])}}
placeholder='Füge hier Notizen, Ideen, Pläne ein'
/> </div> : ""}
</div>
</>
))
}
</>
)
}
export default GoalItems
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
