As the title says, I have fetched data from API on a component. I want that component to just act like a "store" for the fetched data, meanwhile, rendering those data on to another component. How do I do that if that's possible?
This is Fetch.js which is supposed to get data from the API and store it in person
of state
. Now I want to break the object stored in person
and separate into different var
like for fname
, lname
, etc.
import React from "react";
export default class Fetch extends React.Component {
state = {
loading: true,
person: null,
};
async componentDidMount() {
console.log("mounted");
const url = "https://api.randomuser.me/";
const response = await fetch(url);
const data = await response.json();
this.setState({
loading: null,
person: data.results[0],
});
}
render() {
return console.log(this.state.fname);
}
}
Now that everything said above is done, I have another file Main.js
where I want to display the fetched data (broken into each variable like fname,lname) from Fetch.js
.
import React from "react";
export default class Main extends React.Component {
render() {
return (
<div>
{this.state.loading || !this.state.person ? (
<div>Loading</div>
) : (
<div>
Name: {this.state.fname} {this.state.lname}
</div>
)}
</div>
);
}
}