React components are failing to display data as expected

I need to display certain data based on the id provided in the url. When I use console.log() with res.json, I can see the data but I'm unsure how to pass it to the 'articleComponent'.

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 = position_name;
    workplace_name = workplace_name;
  }

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

export default Articles;

The console.log() shows 'pending' but all objects are visible.

This component is accessible after clicking this link:

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

Answer №1

You haven't utilized the response from the fetch call.

In a functional component of React, the function itself serves as the render function. This function operates synchronously, meaning that an async call cannot be directly placed within the function body.

One approach is to make the fetch call within the componentDidMount lifecycle hook. Once the call returns, you can store the result in the component state using setState for class components or the useState hook for functional components.

So:

class Articles extends React.Component {
  state = {
    data: undefined
  };

  componentDidMount() {
    const id = "some value";
    fetch(`https://someurl.herokuapp.com/job/${id}`)
      .then(res => res.json())
      .then(response => this.setState({ data: response }));
  }

  render() {
    const pathname = window.location.pathname.split('/');
    const job_id = pathname[pathname.length - 1];
    const job = query(job_id);
    let position_name;
    let workplace_name;
    console.log(job_id)
    if (job) {
      position_name = position_name;
      workplace_name = workplace_name;
    }


    return (
      <ArticleComponent
        data={this.state.data}
        position_name={position_name}
        workplace_name={workplace_name}
      />
    );
  }
};

export default Articles

Answer №2

It is important to separate the loading logic from rendering in your React components.

  1. Start by creating a state for your data using useState(null) where null serves as the initial state value.

  2. Next, use useEffect to initiate fetching data when the component mounts. Use an empty array [] as the second argument to ensure that the useEffect function only runs once during mount and does not depend on any specific value.

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

const fetchData = async (id, setData) => {
  const response = await fetch(`https://someurl.herokuapp.com/job/${id}`);
  const data = await response.json();
  setData(data);
}

const getJobId = () => {
  const pathname = window.location.pathname.split('/');
  return pathname[pathname.length - 1];
}

const Articles = () => {
  const [job, setJob] = useState(null);
  useEffect(() => {
    fetchData(getJobId(), setJob);
  } ,[]);

  return <>{
      job
      ? <ArticleComponent
        position_name={job.position_name}
        workplace_name={job.workplace_name}
      />
      : <span>loading...</span>
     }</>
};

export default Articles

Answer №3

Hello @Erwin,

I have provided a solution for your query below. Take a look at the CodeSandbox - [https://codesandbox.io/s/mystifying-wave-qxrnp][1]

Feel free to replace the API Endpoint with the one you prefer. I hope this information is useful!

import React from "react";
import ReactDOM from "react-dom";
import ArticleComponent from "./ArticleComponent";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data: undefined
    };
  }

  componentDidMount() {
    const pathname = window.location.pathname.split("/");
    const job_id = pathname[pathname.length - 1];
    console.log(job_id);
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then(response => response.json())
      .then(json => this.setState({ data: json }));
  }

  render() {
    return this.state.data ? (
      <ArticleComponent data={this.state.data} />
    ) : (
      "Loading"
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enabling the acceptance of blank values within an HTML5 date input field

When using an HTML5 date input for a field that corresponds to a nullable datetime column in the database, how can one avoid setting an empty value in the input field? In my AngularJS application, the ng-model is connected to a scope variable with an init ...

Enhancing the aesthetic appeal of a form

I have created a form in HTML that utilizes JavaScript to pull data from a database. I am looking to style the form, but I'm unsure of how to proceed. Below is the form along with some CSS code. How can I integrate the two together? <form id=" ...

Difficulty encountered while attempting to deploy the front-end on Heroku

I recently completed a typeorm project with the following structure: https://i.stack.imgur.com/ReQK1.png Both the client and root directories contain index files located in the src directory. In the package.json file within the client directory, I made a ...

Issue: ngModel: Unassignable Value

I am currently working on a piece of code that dynamically generates a drop-down list. My goal is to set the selected value using ng-repeat. In order to achieve this, I have implemented a function in ng-model. However, I am encountering an issue with the f ...

Exiting callback function in JavaScript

Is there a way to retrieve the return value from within a node.js/javascript callback function? function get_logs(){ User_Log.findOne({userId:req.user._id}, function(err, userlogs){ if(err) throw err; if(userlogs){ ...

Comparing front end automation between JavaScript and Java or Ruby

Could you provide some insights on why utilizing a JS framework like webdriverio is preferred for front end automation over using Selenium with popular languages like Java or Ruby? I understand that webdriverio and JS employ an asynchronous approach to fr ...

What are the best practices for implementing serialization in NestJS?

Recently, I delved into a fresh NestJs project and encountered a hurdle while trying to integrate serialization. The goal was to transform objects before sending them in a network response. Initially, everything seemed to be working smoothly until I attemp ...

Utilizing a keycode within the jQuery plugin without the need to explicitly pass it through options

I am currently working on developing a custom jQuery plugin. My goal is to be able to check the keyCode within the plugin without needing to pass it through as an option parameter. Below, you can see the code snippet that I'm using. It's a bit c ...

Ways to transfer the value of a JavaScript variable to a PHP variable

Similar Question: How can I transfer JavaScript variables to PHP? I am struggling to assign a JavaScript variable to a PHP variable. $msg = "<script>document.write(message)</script>"; $f = new FacebookPost; $f->message = $msg; Unfort ...

Updating access tokens within a Google login component in React by utilizing django-allauth

I recently integrated Google Login into my web app which has a React front-end and Django backend. In the front end, I utilized the react-google-login package to manage all authentication processes, while on the backend, I implemented django-allauth with s ...

What could be causing the error "Unexpected identifier 'trytoCatch' while trying to minify?

I recently updated my script.js and now I'm looking to use "minify" in Node.js to compress it. When I type the command minify script.js > script.min.js into the terminal, I get an error message that says: /node_modules/bin/minify.js:3 import "tryToCat ...

Ajax: The function assigned to the route does not get executed

Pressing a button triggers a confirmation box. If 'ok' is clicked, the div called 'EventData' should display the word 'reached'. The confirmation box appears when the button is clicked, but 'EventData' does not show ...

Ways to integrate debounce functionality in a React text area field

Implementing debounce in the handleInputChange function of my React component was my latest challenge. I wanted to prevent constant rerenders when a user types in the textarea (I even checked this by logging commentBody), but it seems like things didn&apos ...

Calling Node Express request inside a GET route

I am currently utilizing nodejs as an intermediary layer between my public website and an internal server within our network. Through the use of express.js, I have created a basic REST api where the endpoint should trigger a request call to a webservice a ...

Unraveling nested elements with the array map() method in Angular2 and Typescript: Fixing the issue of undefined property reference while mapping

Hey there! I'm currently working with Angular 4 and I have a piece of code that parses data from an API into a TypeScript array of rows. It's important to note that the code functions properly if elements like 'item.tceCampRun' and &apo ...

Is it possible to assign multiple ID's to a variable in jQuery?

I am currently using a script for a slider known as Slicebox, and in order to have different image sizes for mobile and desktop views, I need to duplicate the feature on my website. Although it's not ideal, I really like this slider and want to explo ...

What is the appropriate conversion for a CSS property name starting with -webkit when working with React?

For example, using `-webkit-text-fill-color` resulted in an error when setting it to `'red'`, stating "Using kebab-case for CSS properties in objects is not supported. Did you mean WebkitTextFillColor?" I have attempted `WebkitTextFillColor`, `w ...

I'm looking for the documentation for the latest version of Footable's Events. Can you point me

Does anyone know where to find information on the events that are fired for Footable and how to handle them? I checked the documentation at , but it doesn't provide much detail on events. If you have any resources or suggestions, please let me know! ...

What is the best way to link PostgreSQL with a React frontend using restify?

Login.js This is a Reactjs login page that requires moving to the next page after successful authentication. The database being used is postgreSQL with a table named 'user' for storing usernames and passwords. The development requirements inc ...

Operating with a multidimensional entity

I am aiming for an object structure like this: {"Red 1":53,"Blue 2":26,"Green 3":25} Based on the following example: I attempted to push data from within .each loop into the object. However, due to its multidimensional nature, I'm uncertain how to ...