0

I want to fetch data from server & show it inside tables. When I directly put code inside the render it works. But, When I encapsulate inside the addElementsToDisplay function & call that function inside render method it doesn't work. Actually, the function gets called, but response is not rendered in table format. Below is my code:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Button } from 'semantic-ui-react';
import ResponseRenderer from './responseRenderer';
import "./App.css";

const responseDataContext = React.createContext({});



class App extends Component {
    constructor(props) {
    super(props);
    this.getPastJobs = this.getPastJobs.bind(this);
    this.addElementsToDisplay = this.addElementsToDisplay.bind(this);
    this.state = { pastJobs: [] }
  }

  render() {
    return (
      <div className="App">
        <Button onClick={this.getPastJobs}>Get Past Jobs</Button>
        <h1> Hello, World! </h1>
        {this.addElementsToDisplay()}
      </div>
    );
  }

  addElementsToDisplay() {
    console.log("state: ", JSON.stringify(this.state));
    this.state.pastJobs.map((value, index) => {
      return <ResponseRenderer key={Math.random()} data={value} />
    });
  }


  getPastJobs() {
    fetch('http://localhost:9090/getPastJobs', {
     method: 'POST',
      body: JSON.stringify({})
    })
      .then((response) => {
        if (response.status !== 200) {
          return;
        }
        response.json().then((jobs) => {
          console.log(jobs);
          this.setState({ pastJobs: jobs.data })
        });
      })
      .catch((err) => {
        console.log(err.message, err.stack);
      });
  }
}

export default App;

1 Answer 1

3

You are not returning the response and hence it is not rendered, just return the mapped response and it will work fine

addElementsToDisplay() {
    console.log("state: ", JSON.stringify(this.state));
    return this.state.pastJobs.map((value, index) => {
      return <ResponseRenderer key={Math.random()} data={value} />
    });
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.