0

I am trying to fetch data in componentDidMount lifecycle method of react but I am not getting it.

my method is:

  componentDidMount() {
    const { taskId } = this.props
    getTask(taskId)
    .then(data => {
        console.log(data);
      this.setState({task: data});
    })
  }

my api is:

  export const getTask = (unique_id) =>  {
  console.log(unique_id)
    return fetch('https://punctual-backend-staging.herokuapp.com/api/v1/homeowner_tasks/'+ unique_id).then(res => { 
    return res.json();
    });
  };

this is my whole component:

import React, { Component } from 'react'
import { getTask } from '../../modules/clients';
import ClientTaskShow from '../../components/tasks/ClientTaskShow'

class ClientTaskShowContainer extends Component {
  constructor(props) {
    super(props)

    this.state = {
      messageModalOpen: false,
      selectedPartnerId: null,
      task:{}
    }
  }

  componentDidMount() {
      console.log("hello")
    const { taskId } = this.props
    getTask(taskId)
    .then(data => {
        console.log(data);
      this.setState({task: data});
    })
  }
  render() {
    const taskSelected = this.state.task;
    console.log(taskSelected)
        return (
            <ClientTaskShow 
                task={taskSelected}
            />
        )   
  }
}

export default ClientTaskShowContainer;

code from where calling clienttaskShowContainer:

import React from 'react'
import Head from 'next/head'
import Layout from '../../components/Layout'
import ClientTaskShowContainer from '../../containers/tasks/ClientTaskShowContainer'
import requireAuth from '../../lib/requireAuth'

const ClientTasksShow = ({ query }) => {
  const { taskId } = query
  return (
    <Layout fluid fullHeight clientTaskHeader='true'>
      <Head>
        <title>Client Task Details | Punctual</title>
      </Head>
      <ClientTaskShowContainer taskId={taskId} />
    </Layout>
  )
}

ClientTasksShow.getInitialProps = async ({ query }) => ({
    query
  })

export default requireAuth(ClientTasksShow)

I think its not hitting the API even. Although it hit once I restart the server but not again. I am not able to replicate the problem. At some sites I found we should use .then for API call others says we can't pass perimeter in API call in componentDidMount. What is the exact solution for this. Please help. Thanks in advance.

8
  • 1
    Is it really returning null ? If so, does the API even return JSON? Does the client actually hit the right API? Does fetch reject (attach a .catch to it!) ? Commented Apr 18, 2019 at 6:34
  • I guess even comonentDidMount is not working or called by Commented Apr 18, 2019 at 6:36
  • How do you know that? Does "hello" get logged? Commented Apr 18, 2019 at 6:37
  • no its not logged Commented Apr 18, 2019 at 6:43
  • can you provide a value for the unique_id which is been passed in the api as query params Commented Apr 18, 2019 at 6:45

3 Answers 3

1

This code is working

//Calling component

import React from "react";
import CallComp from "./CallComp";
import ReactDOM from "react-dom";

function App() {
  return (
    <div className="App">
      <CallComp taskId={"7693fbf81a33"} />
    </div>
  );
}

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

// Child Component

import React, { Component } from "react";
import ClientTaskShow from "./ClientTaskShow";

class ClientTaskShowContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      task: {}
    };
  }

  componentDidMount() {
    const { taskId } = this.props;
    fetch(
      `https://punctual-backend-staging.herokuapp.com/api/v1/homeowner_tasks/${taskId}`
    )
      .then(response => response.json())
      .then(data => this.setState({ task: data }))
      .catch(error => console.log("the error is", error));
  }
  render() {
    const taskSelected = this.state.task;
    console.log("task selected is ", taskSelected);
    return (
      <div>
        {Object.keys(taskSelected).length ? (
          <ClientTaskShow task={taskSelected} />
        ) : (
          <div>No data to show</div>
        )}
      </div>
    );
  }
}

export default ClientTaskShowContainer;

// Demo ClientTaskShow

import React from "react";

const ClientTaskShow = ({ task }) => {
  return <h1>{task.unique_code}</h1>;
};

export default ClientTaskShow;
Sign up to request clarification or add additional context in comments.

4 Comments

I have added demo ClientTaskShow for your reference, you could use any component that is accepting the task data from api. You need to change path for ClientTaskShow as well.
like you used an extra div same if I am using this is working but when using my component it is not
In react there should always be a single parent (root element), you could use <Fragment /> or just <></> to avoid <div> wrapping to solve this.
Thanks dude this was pretty helpful
1

Actually its working

enter image description here

console.log(data) returns error message from api

Comments

0

You should return promise from function to know api request is resolved or not

try this:

export const getTask = (id) => {
    return new Promise(function (resolve, reject) {
        fetch('https://punctual-backend-staging.herokuapp.com/api/v1/homeowner_tasks/' + id).then((res) => {
            resolve(res.json())
        })
    });
}

And call like this:

componentDidMount() {
    getTask(1).then((data)=>{
        console.log(data);
    });  
}

You can replace params with your id

Hope this helps.

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.