brunohg
brunohg

Reputation: 37

How to search keyword into api with React Query

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);
  })
);

Upvotes: 0

Views: 791

Answers (1)

TkDodo
TkDodo

Reputation: 28903

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);
    })
  });
 
};

Upvotes: 2

Related Questions