How can I use the value returned in the export function in another component? I have a string value (url) in export function header.js
export default function Header() {
const [countries] = useState([
{ code: 'tr', title: 'Tr' },
{ code: 'gb', title: 'En' },
]);
const [toggleContents, setToggleContents] = useState(<MdLanguage />);
const [selectedCountry, setSelectedCountry] = useState();
if (selectedCountry === "tr") {
getLang("tr");
}
else if (selectedCountry === "en") {
getLang("en");
}
else {
getLang("en");
}
api.js (my databse address localhost:8080/product/en or http://localhost:8080/product/tr )
export const function getLang = async (param) => {
const url = ProductUrl param;
return url;
};
I need to call this url in axios in useeffect in other component.
navbar.js (navbars menu turkish or english so if dropdown select tr , url tr // if dropdown select english , url en)
useEffect(() => {
axios
.get(how?)
.then(response => setData(response.data))
.catch(error => console.log({ error }));
}, []);
thank you.
CodePudding user response:
You need to import it in the component where you want to use it as ---> import {a} from "filedirectory" then use it in the component by calling that function as
const urlValue = a()
CodePudding user response:
useEffect(() => {
const url = a(params);
axios
.get(url)
.then(response => setData(response.data))
.catch(error => console.log({ error }));
}, []);
CodePudding user response:
// getUrl.js
export const getUrl = (params) => {
return ProductUrl params;
}
// or export default
// export default function getUrl(params) {
// return ProductUrl params
// }
Import it into where you want
import { getUrl } from './your-path'
// or import default
// import getUrl from './your-path'
React.useEffect(() => {
const url = getUrl(params)
const fetchData = async () => {
try {
const response = await axios.get(url)
// do something with reponse
} catch (error) {
// handle err
}
}
fetchData()
}, [params])