Home  >  Q&A  >  body text

Simple way to parse JSON data into TypeScript objects using React-Query and Axios

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粉621033928P粉621033928299 days ago466

reply all(1)I'll reply

  • P粉310931198

    P粉3109311982024-01-17 00:36:18

    Found a solution.

    Need to use an array instead of a single object.

    reply
    0
  • Cancelreply