I am practicing React now and I have a task that I am not sure how to do The main idea is to filter tasks in todos list when you type user ID I created another button and when you type user's id it will show exact user's tasks I did filter tasks as well just for practice, but don't know how to filter user's tasks when you type his id
upd: the problem seems like when you type something in input type becomes string, but I need number
import React from "react"
import {useState, useMemo, useEffect} from "react"
function App() {
const [tasks, setTasks] = useState([])
const [completed, setCompleted] = useState(false)
const [title, setTitle] = useState("")
const [userId, setUserId] = useState(1)
const onToggleFilter = () => {
setCompleted(!completed)
}
const onTitleChange = (event) => {
setTitle(event.target.value)
}
const onUserChange = (event) => {
setUserId(event.target.value)
}
let filteredTask = useMemo(() => {
console.log("Filter by status")
return tasks.filter((task) => task.completed === completed)
}, [tasks, completed])
//console.log("Rerender")
if(title) {
filteredTask = filteredTask.filter((task) => task.title.indexOf(title) >= 0)
}
if(userId) {
filteredTask = filteredTask.filter((item) => item.userId === userId)
}
console.log(userId)
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos")
.then(response => response.json())
.then(todos => setTasks(todos))
}, [])
return(
<div className="App">
<h1>Task list</h1>
<div>
<button onClick={onToggleFilter}>
{
completed ? "Show tasks in work" : "Show completed tasks"
}
</button>
<br/>
<br/>
<input onChange={onTitleChange}/>
<input onChange={onUserChange}/>
<br/>
<br/>
{
filteredTask.map((task) => <div key={task.id}>{task.title}</div>)
}
</div>
</div>
)
}
export default App
CodePudding user response:
You need to pass buttons with separate users and they will give you the userId onClick. Also, you are using the same variable userId for two different purposes which will throw an error, please use different variables for different purposes.
CodePudding user response:
Use parseInt
to convert string to number.
const onUserChange = (event) => {
setUserId(parseInt(event.target.value))
}