0

How can I use the "keyword" from the params into my axios get request? My Approach is not working,

// Front End Code

const ComprasLista = () => {
  const { keyword } = useParams();
  

  const compras = useQuery("compras", ({ keyword = "" }) => {
    return axios
      .get(`https://582821e.sse.codesandbox.io/api/compras?keyword=${keyword}`)
      .then((res) => res.data);
  });

  
  // 
};

export default ComprasLista;

// Back End Code

router.get(
  "/",
  asyncHandler(async (req, res) => {
    const keyword = req.query.keyword
      ? {
          fornecedor: {
            $regex: req.query.keyword,
            $options: "i"
          }
        }
      : {};
    const compras = await Compras.find({ ...keyword });
    res.json(compras);
  })
);

1 Answer 1

2

parameters to your query should go to your queryKey, which is then passed to your query function:

const fetchCompras = ({ queryKey: [,keyword] }) => {
    return axios
      .get(`https://582821e.sse.codesandbox.io/api/compras?keyword=${keyword}`)
      .then((res) => res.data);
  })

const ComprasLista = () => {
  const { keyword } = useParams();
  
  const compras = useQuery(["compras", keyword], fetchCompras);
 
};

of course you can also just closure over it, but the important part is to put it into the query key so that you get automatic refetches as the key changes:

const ComprasLista = () => {
  const { keyword } = useParams();
  
  const compras = useQuery(["compras", keyword], () => {
    return axios
      .get(`https://582821e.sse.codesandbox.io/api/compras?keyword=${keyword}`)
      .then((res) => res.data);
    })
  });
 
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.