This is the JSON data I received from the server:
{"id" : 1, "text_data": "example data"}
Now I'm trying to parse this JSON data into a TS object:
export interface IncomingData { id: number; text_data: string; } function App() { // 它可以重写为 'await axios.get<IncomingData>('http://localhost:3000/api')' 并删除 useQuery 的 turbofish 语法。没有任何变化。 let json_object = useQuery<IncomingData>("data_ex_key", async () => { try { const response = await axios.get('http://localhost:3000/api'); return response.data; } catch (err) { throw err } }); if (json_object.data !== undefined) { console.log(json_object.data.text_data); } }
In the console I get the text undefined
. The problem is that I have debugged this code using the react-query debugger and it shows that the json_object
query successfully fetched the data. I can access the data but not its properties like text_data
.
Found a solution.
Need to use an array instead of a single object.