I have a component that concatenates several strings into one string, which I declare as a const to use as a URL. How to I use this const in another component, which needs the URL to fetch data?
Example of the code:
URLconcatenate.js creates the const URLstring
const string01 = 'www.'
const string02 = 'apple';
const string03 = '.com'
const urlString = string01 + string02 + string03
//this validates the concatenation
console.log(urlString);
function URLconcatenate() {
return (
<div>
{urlString}
</div>
)
}
export default URLconcatenate
Datafetch.js (needs to receive and use the const urlString
import { useState, useEffect } from 'react';
import URLconcatenate from './URLconcatenate';
const Datafetch = () => {
const [price, setPrice] = useState([]);
useEffect(() => {
fetch(urlString)
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
setPrice([data]);
});
}, []);
return (
<div>
{price.map((thePrice) => (
<p key={thePrice.c}>Today's price for AAPL is: ${thePrice.c}</p>
))
}
</div >
);
};
export default Datafetch
>Solution :
Make sure to export your urlString
// URLconcatenate.js
export const urlString = string01 + string02 + string03
// Datafetch.js
import { urlString } from './URLconcatenate';