Home > front end >  Destructuring object in array on next js backend
Destructuring object in array on next js backend

Time:05-22

How can I resolve this? I put req.query parameter with an array but I can't destructure or use items from my array. I getting on my next.js API backend just [object Object] or undefined. How can I select what I want?

const fetchData = async (queryKey: any, manufacturer) => {
  const res = await fetch(
    `http://localhost:3000/api/data/get?&manufacturer=${manufacturers}`
  );
  return await res.json();
};

const manufacturers = [
  { name: 'Samsung', type: 'TV' },
  { name: 'Nokia', type: 'Phone' },
];

const { data, status } = useQuery(
   ['somekey', manufacturer],
   ({ queryKey }) => fetchData(queryKey, manufacturer)
);

And here is the next API where I can't get values from the query I getting just [Object, Object] or undefined,

this code work if just put on the front end just a simple array or string without an object in variable manufacturers.

But how i can get values from [Object, object]? I try it

const { name, type } = req.query.manufacturer
const { name, type } = req.query.manufacturer[0]

or select just one field dont work to = const some = req.query.manufacturer[0].name

export const handler = async (
  req: NextApiRequest,
  res: NextApiResponse<Data>
) => {
  const { name, type } = req.query.manufacturer;
};

export default handler;

CodePudding user response:

Could you try const [{ name, type }] = req.query.manufacturer? Seems to be what you need

edit

Also, you may want to try instead of http://localhost:3000/api/data/get?&manufacturer=${manufacturers} => http://localhost:3000/api/data/get?&manufacturer=${encodeURIComponent(JSON.stringify(manufacturers))}

It probably will be accessible with { name, type } = req.query.manufacturer then

  • Related