简体   繁体   中英

I made an API call fetching data from it on a React component and passed it on to a state. I want to use the same data on another component too

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>
       );
      }
     }

You can pass that data in properties from a parent component to children:

function ParentComponent() {
  const data = fetch(...);

  return <ChildComponent data={data} />
}
...
function ChildComponent(props) {
  const data = props.data;

  ...
}

But if you might need that data in many components (or there are a bunch of layers to the child component) it would be way more convenient to use React's Context for this purpose: https://uk.reactjs.org/docs/context.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM