I am getting response from server and create model class of QuestionInfo type. then I am assigning that object into state array. Now I am getting object from array. Code is given below.
const [questions, setQuestions] = useState<[QuestionInfo] | undefined>();
const [questionObj, setQuestionObj] = useState<QuestionInfo | undefined>()
useEffect(() => {
testAPICall();
}, []);
//Method Call
const testAPICall = async () => {
try {`enter code here`
const response = await fetch("URL",
{`enter code here`
method: "get",
headers: {
"Authorization": "",
}
});
const json = await response.json();
console.log('Success :', json.data);
setQuestions(json.data);
setQuestionObj(questions[0])//This Line giving me error
} catch (error) {
console.error(error);
console.log('error : ', error);
} finally {
}
}
}
我收到服务器的响应就像
"data": [
{
"question": {
"en": "What are the 3 most important parts of the "18 Months" rule?"
},
"options": {
"en": [
"Product, service & traction",
"Working capital, customer base & strategy",
"Product, service & failure",
"Service, working capital & strategy"
]
},
"_id": "ZZZZZZZ",
"question_type": "single"
},
{
"question": {
"en": "what is the most important thing he should keep in mind?"
},
"options": {
"en": [
"Product specifications",
"Brand strategy",
"Customer's problems",
"Working capital"
]
},
"_id": "YYYYYYY",
"question_type": "single"
}
],
"id": "XXXXXXXXXXX"
}
我将每个对象存储在 QuestionInfo 对象中。如果我正在获取特定对象的对象。然后。我收到错误
我收到类似“'typeof QuestionInfo'类型的参数不能分配给'SetStateAction
答案 0 :(得分:0)
错误告诉您不能设置分配问题信息 |未定义类型到您的状态。
你有两个解决方案。
if (questions[0]) {
setQuestionObj(questions[0])
}
const [questionObj, setQuestionObj] = useState<QuestionInfo | undefined>(