Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
react is trying to render the page even before the params.id is being fetched so only the if statement is being running every time

I want to render the react code when the id in the params match the id in the data but here react tries to render the code even before props.match.params.id is being executed so only the if statement is being executed can you provide me with a solution to solve this.Ive even tried using useParams() but it does not do anything good.

import data from'./data'
import React  from 'react'



export default function Productdisplay(props) {
 
  const y= props.match.params.id
  const product=data.products.find((x) => x.id===y); //An error lies here

  if(!product){
    return(
      <div>No product to display {}</div>
    )
  }
return(
<>
//Here lies the code I want to render when the ids of the url and data  match 
but as React tries to render the code even before the params is being fetched 
only if statement is being rendered can you give me a solution for this
</>
)
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

What you want to use here is a useEffect that contains your conditions/logic that will run when its depecencies change. Here it is Y. Then store the ouput of your logic from the useEffect into a real state (useState) and not a const. From there you'll be able to trigger the re-render you expect.

import React, { useState, useEffect } from 'react';

function Productdisplay(props) {
  const [products, setProducts] = useState();

  useEffect(() => {
    const y = props ? .match ? .params ? .id;
    const findProducts = data.products.find((x) => x.id === y);

    if (findProducts !== products) {
      setProducts(products);
    }
  }, [data?.products, props?.match?.params?.id]);

  if(!products) return null; 
  return (
    <div>
      // ...
    </div>
  );

I suggest you to read this https://reactjs.org/docs/hooks-effect.html

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!