Simple way to parse JSON data into TypeScript objects using React-Query and Axios
P粉621033928
P粉621033928 2024-01-16 12:45:51
0
1
418

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.

P粉621033928
P粉621033928

reply all(1)
P粉310931198

Found a solution.

Need to use an array instead of a single object.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!