i am trying to use search filter to search all the element of the table but i am getting this error record.filter is not a function and if removed it then i am getting this error record.map is not a function. so i don't understand the problem i can't find the solution for this
import { useEffect, useState } from "react";
import axios from "axios";
import React from 'react';
function Read() {
const [record, setRecord] = useState('');
const [searchTerm, setSearchTerm] = useState('');
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/comments')
.then((response) =>{
console.log(response.data);
setRecord(response.data);
})
}, [])
return (
<>
<input type="text" onChange={(e) => { setSearchTerm(e.target.value) }} placeholder="Search" />
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Role</th>
</tr>
</thead>
<tbody>
{record
.filter((val) => {
if (searchTerm === "") {
return val;
}
else if (
val.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
val.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
val.body.toLowerCase().includes(searchTerm.toLowerCase())
) {
return val;
}
return false;
})
.map((demo, i)=> {
return(
<tr key={i}>
<td>{demo.name}</td>
<td>{demo.email}</td>
<td>{demo.body}</td>
</tr>
)
})}
</tbody>
</table>
</>
);
}
export default Read;
CodePudding user response:
I think because of rendering issue, sometimes record is just empty value.
you just add if (!record) return <></>
this code above return.
And you'd better modify your initial value of record to []
not ''
import { useEffect, useState } from "react";
import axios from "axios";
import React from 'react';
function Read() {
const [record, setRecord] = useState([]); //