Home > Enterprise >  How to use fetch() in react front-end to get data from express back-end?
How to use fetch() in react front-end to get data from express back-end?

Time:12-19

I'm trying to make a full-stack web-app using react and express. It's going pretty well atm but here's my problem:

So I have express running in back-end. All paths are used by react router except for '/api'. At the '/api/blogposts' path my server.js send the results of a query I made to the mySQL server. (I've checked it and this part works. If I browse to /api/blogposts my browser shows a json with the contents of my blogposts table).

My problem is with getting it to show in my react front-end. I'm trying to use fetch() but it doesn't work. Here's my code for the component that is supposed to fetch the blogposts:

import React from 'react';
import './Blogposts.css';
import SingleBpost from '../SingleBpost/SingleBpost.js';

class Blogposts extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            receivedPosts: {}
        };
    }
    generateBlogpost() {
        fetch("/api/blogposts")
            .then((data) => {
                console.log(data);
            })
            .then((results) => {
                this.state.receivedPosts = results;
            });
        return this.state.receivedPosts;
    }
    render() {
        return(
            <div id="Blogposts">
               {this.state.generateBlogpost()}
            </div>
        );
    }
}


export default Blogposts;

Just to clarify the {this.state.generateBlogpost()} in the render method is just to check if I can get the data for now. Once this works I will feed it into another component's props like this:

<SingleBpost title={this.state.generateBlogpost().title} date={this.state.generateBlogpost().date} author={this.state.generateBlogpost().author} body={this.state.generateBlogpost().body} />

Anyways: does anyone know why this doesn't work? I've tried a few things but I just can't get it to work. What am I doing wrong?

Thanks in advance for any help!

CodePudding user response:

You need to set the state of the variable receivedPosts in the fetch function like this :

this.setState({receivedPosts: results});

Also, you can call the function generateBlogpost() at the load of the Component Blogposts by adding the following function :

componentDidMount() {
 this.generateBlogpost();
}

CodePudding user response:

this one is useless

.then((results) => {
                this.state.receivedPosts = results;
            });
        return this.state.receivedPosts;
    }

//instead you should use setState({receivedPosts: data.data})

  • Related