I am trying to build a web application with Wordpress REST API.
I am making an initial GET request to an endpoint and parsing through the res.data
to get some values. But, one of the values featured_media
is a parameter for the 2nd GET request I am trying to make. I am finding it difficult to get this value out of that state onto the second GET request.
Here are the states.
state = {
graduatepost: {},
category: '',
featured_media: '',
imgURL: '',
isLoaded: false
}
Here is componentDidMount()
componentDidMount() {
const { featured_media } = this.props;
axios.get(`http://localhost:8000/wp-json/wp/v2/blog/${this.props.match.params.id}`)
.then(res => this.setState({
graduatepost: res.data,
category: res.data.categories[0],
featured_media: res.data.featured_media,
isLoaded: true
}))
.catch(err => console.log(err));
const getImageURL = axios.get(`http://localhost:8000/wp-json/wp/v2/media/${featured_media}`);
Promise.all([getImageURL]).then(res => {
this.setState({
imgURL: res[0].data.media_details.sizes.full.source_url,
isLoaded: true
});
});
}
1st GET request: http://localhost:8000/wp-json/wp/v2/blog/${this.props.match.params.id}
2nd GET request: http://localhost:8000/wp-json/wp/v2/media/${featured_media}
As you can see the 2nd request requires the value featured_media
which is in the response of the 1st GET request.
I am rendering the component like this.
render() {
const { graduatepost, category, isLoaded, featured_media, imgURL } = this.state;
if(isLoaded) {
return (
<Styles>
<Fragment>
<Link to='/graduate-posts'>Go Back</Link> // Ignore this
<hr />
<h1>{graduatepost.title.rendered}</h1>
<div dangerouslySetInnerHTML={{__html: graduatepost.content.rendered}}></div>
<h4>Category: {category}</h4>
<h4>featured_media: {featured_media}</h4>
<h4>imgURL: {imgURL}</h4>
</Fragment>
</Styles>
)
}
return <h3>Loading...</h3> // Ignore this
}
When I do the render the component. There is a 404 console error for the 2nd GET request, which states.
GET http://localhost:8000/wp-json/wp/v2/media/undefined 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)
I am assuming this is because featured_media
is empty/undefined but I cannot figure out how to extract that value from the 1st GET request, response.
This may seem like an obvious one but I'm relatively new to working with React.js and APIs together. Your help would be greatly appreciated.
Thank you.