This is the route code form express backend and MongoDB database and normal call from frontend with fetch("/")
it was returning index.html code and on adding fetch("http://localhost:9000")
it was returning CORS Error so I added app.use(cors())
.
router.get("/", async (req, res) => {
Journal.find({}, function (err, journals) {
if (err) {
res.send("Something went wrong");
}
res.json(journals);
});
});
This is the axios and fetch request made from reactjs frontend, on making fetch and axios call on "/" as at the backend nothing was coming up only index.html code was being returned so therefore I started using "http://localhost:9000" then data was coming but this localhost problem came up.
const [journals, setJournals] = useState([
{ title: "Day 1", content: content_string },
]);
useEffect(() => {
getJournalData();
});
// const getJournalData = async () => {
// try {
// const res = await fetch("http://localhost:9000/");
// const data = await res.json();
// setJournals(data);
// console.log(data);
// } catch (err) {
// console.error(err);
// }
// };
const getJournalData = () => {
axios
.get("http://localhost:9000/")
.then((res) => {
setJournals(res.data);
})
.catch((err) => console.error(err));
};
This is chrome-dev-tools network tab:
Console Content
React is working at localhost:3000 Express is working on locahost:9000
proxy:http://localhost:9000 is added in package.json in frontend react app
Please tell me what is goind and how can I fix it. Thankyou
CodePudding user response:
Without using an array of dependencies, every change will trigger your useEffect
to run again.
So every re-render, every changing state will cause you to create another Api calls.
Let's talk about variant useEffect:
useEffect(() => {
// invoking on every re-render
})
useEffect(() => {
// invoking on component did mount (once)
}, [])
useEffect(() => {
// invoking on component did mount and with every change on counter
}, [counter])
So, change your code:
useEffect(() => {
getJournalData();
}, []);