1

I'm stuck with an issue that I have with React Router, I'm trying to render a component inside of a card but for some reasons, the data are not displaying:

     <Link             
         to={{
         pathname: `/job/${job._id}`,
         state: job}}>
         <p className="place">{job.workplace_name}</p>
         <p className="location-job">{job.location}</p>
                      </Link>

on Click to this link I would like this to render:

const Articles = () => {

  const query = (id) => {
    fetch(`https://someurl.herokuapp.com/job/${id}`).then(res => 
 console.log(res.json()))
  }

  const pathname = window.location.pathname.split('/');
  const job_id = pathname[pathname.length - 1];
  const job = query(job_id);
  let position_name;
  let workplace_name;

  if (job) {
    position_name = job.position_name;
    workplace_name = job.workplace_name;
  }


  return (
    <ArticleComponent
      position_name={position_name}
      workplace_name={workplace_name}
    />
  );
};

Everything is displaying on the console.log but for some reason, the job is not defined, so I can't pass any data to the ArticleComponent, any ideas? Thanks in advance for the help, I have been stuck for quite some time now.

Grzegorz Smulko
  • 2,525
  • 1
  • 29
  • 42

2 Answers2

0

Are you sure that the problem is not caused by the usage of a backtick (`)?

How about changing

fetch(`https://someurl.herokuapp.com/job/${id}`).

to

fetch("https://someurl.herokuapp.com/job/${id}").

?

See Usage of the backtick character (`) in JavaScript? for a more detailed explanation.

Grzegorz Smulko
  • 2,525
  • 1
  • 29
  • 42
0

I would make your component stateful to make it easier to properly handle the asynchronous API call. Make sure you await, update state, then properly render your components with api result data passed as props. Also, use react router's search property in your Link component to make it easy to access your query parameter.

<Link
  to={{
    pathname: // set path
    search: { job_id: 1 }
    state: // set any initial state your'd like to pass
  }}
/>

/////

class Article extends React.Component {
   constructor(props) {
     super(props)
     this.state.apiRes = null;
   }

  async ComponentDidMount() {
    const id = this.props.match.params.job_id
    const apiRes = await fetch(`https://someurl.herokuapp.com/job/${id}`).then(res => res.json()).then(finalRes => finalRes);
    this.setState({ apiRes })
  }

   render() {
      if(this.state.apiRes) {
          const position_name = this.state.apiRes.position_name
          const workpalce_name = this.state.apiRes.workplace_name  
       return (
         <ArticleComponent
           position_name={position_name || null}
           workplace_name={workplace_name || null }
         />
        );
       } else {
        return null
       } 
     }
  }




Greg Brodzik
  • 1,765
  • 7
  • 9