How to get json data with React, fetch and Rest api?

Asked

Viewed 1,187 times

0

I’m doing some studies with React, and for that I’m pulling a JSON from Restapi Wordpress.

When I put something like fetch("https://pulsemaker.com.br/wp-json/wp/v2/posts/179") It works just fine, but when I pass Querys like fetch("https://pulsemaker.com.br/wp-json/wp/v2/posts/?slug=10-projetos-para-fazer-com-arduino") he doesn’t pull the dice.

  • Post the code. Without code we can’t help you.

  • I noticed that in the URL with filters has a array surrounding the object and when there is no filter is the direct object. You may have to make a small change to your code.

  • is an array yes, but I did some tests and it made no difference the array, what I noticed is that the query generates the error (think.. rs)

  • But console.log shows some error?

  • Does not show, shows the error in the browser even though it is Typeerror: Cannot read Property 'rendered' of Undefined

1 answer

0

import React, { Component } from 'react';
import {
    BrowserRouter as Router,
    Route,
    Link
  } from 'react-router-dom';

class Post extends React.Component {
    constructor() {
        super();

        this.state = {
            post: {
                title: {
                    rendered: ''
                },
                content: {
                    rendered: ''
                }
            }
        }
    }
    componentDidMount() {
        var url  = window.location.href;
        var slug = url.split("/")[url.split("/").length -1];
        fetch("https://pulsemaker.com.br/wp-json/wp/v2/posts/179")
            .then(results => results.json())
            .then(results => this.setState({'post': results}));
    }
    render() {
        return (
            <div className="wrapper">
               <h1>{this.state.post.title.rendered}</h1>
                <article dangerouslySetInnerHTML={{ __html: this.state.post.content.rendered }} />
            </div>
        );
    }
}
export default Post

  • Guys, we got it! What happens is that the wordpress API puts an array right at the beginning when you pull the data using Slug, it doesn’t happen if you pull using the post id. As I needed by Slug to use on the route, I made some changes. If you have any questions about how to use React with Wordpress, you can see what I’m doing on my github https://github.com/rodrigopulse/react-wordpress

Browser other questions tagged

You are not signed in. Login or sign up in order to post.