jeudi 28 janvier 2021

Restful API Graphql with ExpressJs: Get document by Id not working

I am using graphql, express and react to build my app, and it is a job board app and I succeeded in query in the backend, this is how I did

query

now, I want to fetch it throughout API requests.js

const endpointURL = 'http://localhost:9000/graphql';

export async function loadJob(id) {
  const request = await fetch(endpointURL, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
    },
    body: JSON.stringify({
      query: `
          query JobQuery($id: ID!) {
            job(id: $id) {
              id
              title
              company {
                id
                name
              }
              description
            }
          }
                `,
      variables: {id},
    }),
  });
  const requestBody = await request.json();
  console.log(requestBody, 'json');
  return requestBody.data.job;
}

and import it in other components jobDetail.js

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { loadJob } from './requests';

export class JobDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {job: null};
  }

 async componentDidMount(){
  const {jobId} = this.props.match.params;
  const job = await loadJob(jobId);
  
  this.setState({job});
 }

  render() {
    const {job} = this.state;
    console.log(job, "job");
    return (
      <div>
        <h1 className="title">{job.title}</h1>
        <h2 className="subtitle">

      <Link to={`/companies/${job.company.id}`}>{job.company.name}</Link>
    </h2>
    <div className="box">{job.description}</div>
  </div>
);

} }

as you can see in file requests.js, i tried to print out request 's body but is not be called in the console, in file jobDetail.js, i did the same to print out job but it still null but the jobId is valid

Please show me how to solve it, thank you so much and have a good day




Aucun commentaire:

Enregistrer un commentaire