Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
React js, confuses fetch url with another fetch

In my Home component, I have this fetch function

export default function Home() {
  const { rootUrl } = useContext(UserContext);
  useEffect(() => {
    fetch(`${rootUrl}/api/products/featuredProducts`)
      .then((result) => result.json())
      .then((result) => {
        console.log(result);
      });
  }, []);
}

That is supposed to pull products from the db which are featured. But every time I try to run that fetch it confuses with another fetch in my app which is the get single product fetch, which is this code:

export default function ProductView() {
  const { productId } = useParams();
  const { rootUrl } = useContext(UserContext);
  const { addToCart } = useContext(UserContext);
  const [productData, setProductData] = useState("");

  useEffect(() => {
    fetch(`${rootUrl}/api/products/${productId}`)
      .then((result) => result.json())
      .then((result) => {
        setProductData(result);
      });
  }, []);

I will get an error in my backend API with this message:

 CastError: Cast to ObjectId failed for value "featuredProducts"

That "featuresProducts" is my endpoint for my first fetch. It seems that something is confusing it as my parameter ID for my second fetch url in my ProductView component, this fetch below:

fetch(`${rootUrl}/api/products/${productId}`)

I don't understand why is this happening as my other routes with "api/products/plus other endpoints here" work just fine, it's just this my new addition to fetch featured products won't work

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You defined your route as /products/:id, so whenever your backend sees a route like /products/anything it will automatically (and correctly) assume the anything is id. You can combat this in various ways.

What I would do is, create one route for fetching with id:

/products/id/:id

and another for featured:

/products/featured

in your backend.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda