TeslaLDead
TeslaLDead

Reputation: 93

React component is unable to fetch data from api

This is my userinfo.js which fetches data from app.js which is to be displayed here.

import React, { Component } from 'react';
import axios from 'axios';

class UserInfo extends Component {
    constructor() {
        super();
        this.state = {
          error: null,
          isLoaded: false,
          persons: []
        };
    }
    componentDidMount() {
    fetch("http://localhost:5000/api/userinfo")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            persons: result
          });
        }) 
       .catch(
        (error) => {
          this.setState({
            isLoaded: true,
            error: error
          });
        });
    }

    render(){
        const { error, isLoaded, persons } = this.state;
        if (error) {
          return <div>Error: {error}</div>;
        } else if (!isLoaded) {
          return <div>Loading...</div>;
        } else {
            return(
              <div>
                <h1>profile</h1>
                <h1>{ this.state.persons.map(person => <li key={this.state.persons.id}>{person.firstName}</li>)}</h1>
              </div>
            );

        } 
    }
}
export default UserInfo;

And API is(app.js in node server):

app.get('/oauth/linkedin', function(req, res) {
    // This will ask for permisssions etc and redirect to callback url.
    Linkedin.auth.authorize(res, scope);
});

app.get('/profile/signin-linkedin',function(req,res){
	 Linkedin.auth.getAccessToken(res, req.query.code, req.query.state, function(err, results) {
        if ( err )
            return console.error(err);
        console.log(results);
        request({url:'https://api.linkedin.com/v1/people/~?format=json&oauth2_access_token='+results.access_token},function(error,response, body){
	        if (!error && response.statusCode == 200) {
				console.log('hurray');
				//console.log(response);
				console.log('body is :'+body);
				info = JSON.parse(body);
				info1[0] = info;
				console.log(info1);
				console.log(info.firstName);
				fN = info.firstName;
				lN = info.lastName;
				id = info.id;
				res.redirect('http://localhost:3000/userinfo');
			}
			else{
				console.log(body);
			}
        })
    });
});

app.get('/api/userinfo',function(req,res){
	console.log('hii');
	res.setHeader('Content-Type', 'application/json');
	res.send(info1);
	
});


app.listen(5000,process.env.IP);

I am getting the following error: Objects are not valid as a React child (found: TypeError: Failed to fetch). If you meant to render a collection of children, use an array instead. Even though i am passing a array from app.js , i am getting error. Can anyone tell me how to resolve it??

Upvotes: 0

Views: 1172

Answers (2)

Praseel Narayan
Praseel Narayan

Reputation: 1

Change this

this.setState({
  isLoaded: true,
  persons: result
});

To this

this.setState=({
  isLoaded: true,
  persons: result
});

Upvotes: 0

Brett Merrifield
Brett Merrifield

Reputation: 2310

The problem is you are saving an error object to state and rendering it as a react child (objects are not valid react as a child). What is happening is your .catch((error) => ... comes back as an error object, not a string. So when you setState you are setting your this.state.error to an error object. SO in your render you do if (error) { return <div>Error: {error}</div>; } but the error you are referencing is an object not a string which is an invalid react child. In conclusion, you should save the error message to state instead.

.catch(
  (error) => {
    this.setState({
    isLoaded: true,
    error: error.message // error.message is a string
  });
});

As far as the error with fetching. Use Postman or something similar to debug why you are receiving an error from your server in the first place.

Upvotes: 1

Related Questions