I am doing a project in React, where after I type a value and then click on search button, the app searches if the id exists in the database. If so, it displays the result of the search in the same page. I am having trouble assigning the value of the search and then displaying it. When I try to assign the result of the search to an array, it gives me the error:
JavaScript
x
3
1
Type 'DocumentData[]' is not assignable to type 'Dispatch<SetStateAction<Identification[]>>'.
2
Type 'DocumentData[]' provides no match for the signature '(value:SetStateAction<Identification[]>): void'.
3
When I did a console.log of just the data in no variable, I can get the results, but I need it in the setId variable.
Here is the code:
JavaScript
1
49
49
1
import React, {ChangeEvent} from "react";
2
import { useState,useEffect } from "react";
3
import LongText from "../atoms/LongText";
4
import AppListBI from "./AppListBI";
5
import {Identification} from "../../assets/Person/Person";
6
import db from "../../firebase.config"
7
8
const Core = () => {
9
var [input, setInput] = useState('')
10
const [showResults, setShowResults] = React.useState(false)
11
var [person, setId] = useState<Identification[]>([]);
12
13
const fetchBI = async () => {
14
const ref=db.collection('id').where('numberId','==',input).get().then((snapshot) => {
15
snapshot.docs.forEach(doc =>{
16
setId=[person,doc.data()]
17
//I also tried
18
setId=doc.data()
19
})
20
})
21
}
22
23
return (
24
<>
25
<div className="mx-7">
26
<span className="font-bold text-xl"><h5>Pesquisar:</h5></span></div>
27
<div className="flex justify-center">
28
<LongText placeholder="Pesquisar Id" onChange={
29
(e: ChangeEvent<HTMLInputElement>)=>setInput(e.target.value)}
30
onClick={useEffect(()=>{
31
setShowResults(true)
32
fetchBI();
33
})}/>
34
</div>
35
36
<div className="flex justify-center">
37
<span className="my-4 w-11/12">
38
{ showResults ? <AppListId persons={person} /> : null }
39
</span>
40
</div>
41
42
</>
43
44
);
45
46
}
47
48
export default Core;
49
Advertisement
Answer
After long days I found the solution: I traded this:
JavaScript
1
5
1
const fetchBI = async () => {
2
const ref=db.collection('id').where('numberId','==',input).get().then((snapshot) => {
3
snapshot.docs.forEach(doc =>{
4
setId=[person,doc.data()]
5
to:
JavaScript
1
30
30
1
const fetchBI = async () => {
2
try{
3
var people : ID[] = []
4
await db.collection('id').where('numberId','==',input).get().then(
5
querySnapshot=>{
6
const data = querySnapshot.docs.map(
7
doc=>{
8
let dat = doc.data()
9
people.push({
10
numberId: dat.numberId,
11
name: dat.name,
12
dateOfBirth: dat.dateOfBirth,
13
placeOfBirth: dat.placeOfBirth,
14
fathersName: dat.fathersName,
15
mothersName: dat.mothersName,
16
gender: dat.gender,
17
profession: dat.profession,
18
dateOfIssue: dat.dateOfIssue,
19
expirationDate: dat.expirationDate
20
21
})
22
})
23
setId(people)
24
}
25
)
26
}catch (error) {
27
console.log(error.message)
28
}
29
}
30