Hello Guys, This article about usage of single value in different functional components in react
In case of example with API calls from react, will use `fetch` for hit the endpoints and save response in state and use or map the response data in UI
So in every API call will use endpoint(URL), for example we have call create, read, update and delete in four different components, generally will use full endpoint in every component like below example.
Create.js
const endpoint = 'http://locolhost:3045/sample/project/todo/create';
fetch(endpoint, options)
.then((res) => res.json())
Update.js
const endpoint = 'http://locolhost:3045/sample/project/todo/update';
fetch(endpoint, options)
.then((res) => res.json())
Delete.js
const endpoint = 'http://locolhost:3045/sample/project/todo/delete';
fetch(endpoint, options)
.then((res) => res.json())
Read.js
const endpoint = 'http://locolhost:3045/sample/project/todo/list';
fetch(endpoint, options)
.then((res) => res.json())
In above four pages we created a constant variable which is ‘endpoint’, in case of change in the domain name example my base URL got changed form ‘http://locolhost:3045/‘ to ‘http://locolhost:3049/‘
Or else I have change the folder name from ‘sample‘ to ‘myprojects‘, in this type of cases the API will fail because the path is changed for API, but in our files still we are hitting the old endpoint right!
What is the fix for it, we need to change to new URL in all files/components where ever the old URL is used in existing. this bit complex and take more time to identify the URL in total project
How We Can Make More Simple To Avoid Complexity
Create a sample helper file and add the base URL which is common in all files, make that URL as exported variable and where ever we need we just need to import and use that same URL.
utils.js
export const baseURL = 'http://locolhost:3045/sample/project';
If we create export variable, we can get them via import in other files.
Usage : example in Create.js ( Can use in all files in same way )
import {baseURL} from 'utils.js';
const endpoint = `${baseURL}/todo/create`;
fetch(endpoint, options)
.then((res) => res.json())
Same way we can import in all files. In this case if any change in base url or any folder, simply we need to change in utils file instead of changing in all files.
Hope, It helps…. 🙂
