Reputation: 1031
Enquiry: I have one component that will fetch three different data from a json. But how do I pass a props to make that component realize which data I want to fetch?
Example: App.js will include three duplicates of a single component and pass different props.
<Component nameOfDataToBeFetched={'1'} />
<Component nameOfDataToBeFetched={'2'} />
<Component nameOfDataToBeFetched={'3'} />
But in a receiving component, I want to fetch data from a certain json api using that props.
fetch('www.example.com/api')
.then(response => response.json)
.then(json => setData(json.nameOfDataToBeFetched.value)
I mean, I can just do conditional fetching depending on the props, but is there a way to fetch a specific data using the props?
Upvotes: 0
Views: 431
Reputation: 1292
You can use only one component and pass different props.
componetDidMount(){
fatchData(this.props.nameToBeFetched)
}
componetDidUpdate(prevProps, prevState){
if(prevProps.nameToBeFetched !== this.props.nameToBeFetched){
fetchData(this.props.nameToBeFetched)
}
}
async function fetchData(nameToBeFetched){
}
Upvotes: 0
Reputation: 1035
Will this be answer to yout question?
// Component.js
componetDidMount(){
const url = `example.com/api/${this.props.nameOfDataToBeFetched`;
/*
// Any other composition
const url = `example.com/api?dataName=${this.props.nameOfDataToBeFetched`;
*/
fetch(url)
// ...
}
Upvotes: 1