PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 12, 2022

[FIXED] how to destructure nested data from reactQuery/useQuery in next.js/react.js

 October 12, 2022     axios, ecmascript-6, next.js, react-query, reactjs     No comments   

Issue

const {
  isLoading,
  data: products,
  refetch,
} = useQuery(["products"], () =>
  axios.get(
    `https://product-bazar.herokuapp.com/api/v1/public/product`
  )
);

How can I destruct data from data in this query operations ex:[data?.products]


Solution

You can destructure the nested data from responded data. But the better way to fetch data using useQuery is:

const fetchCartData = async () => {
const { data } = await axios.get(API.GET_ALL_CART_ITEMS, {
  headers: {
    Authorization: token,
  },
});
if (data?.cart_data?.Items === undefined) {
  setCartLoading(false);
  return [];
} else {
  setCartLoading(false);
  return data?.cart_data?.Items ? data?.cart_data?.Items : [];
}};

And then use useQuery to fetch data through fetchCartData() function:

 const {
isLoading,
refetch,
data: cartData,
isError,
error} = useQuery(["cartData"], () => fetchCartData());


Answered By - Mahfuz Rahman
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing