I was getting very high firebase reads from past few days so when checked I found it's because of the useEffect getting fired multiple times. if I change the parameter to [] it don't fetch anything.
I am created a related petition section where petition of particular category will be shown, when I set the parameter to relatedPetition it does work but the useEffect fires multiple times making my firestore reads high and when I just keep it [] it shows nothing in related section
Go back to using [] for the second argument for useEffect. Then change your setRelatedPetition to setRelatedPetition([...somePetition]).
Hey yashraj this is a common problem with the useEffect hook, can i see the code inside the useEffect? so I can be able to help you more, but then to solve the problem add a variable to the dependency array [] a variable that is directly or indirectly affected by updates from data fetched from the firebase api,
would love to see the code, are you calling the api from useEffect hook?
It seems to cause infinite rendering. Why not putting the array stringified? See the link below. https://stackoverflow.com/a/59468261/19622195
Related
I am trying to pass the result of promise fetch from a child to parent component with emit. Emit works perfectly fine before the $fetch where my parent component was able to receive it, however the emit does not work in the image as seen where it is used after $fetch.
I have been trying to solve it for hours but have zero idea on why does it not work. Am learning, so do enlighten me if anyone knows the reason for it.
Thank you very much, appreciative of your help and time.
Cheers.
I tried to emit after fetch to API and expected my parent component to receive the event but it did not.
Are you using the fetch() hook that comes with Nuxt? If so, it should be called outside your methods block and without the '$'. Review the Nuxt Docs on data fetching. You may also want to consider using the 'asyncData' hook depending on your use case.
Also, should it be a DELETE method instead? I don't know your API, but I assume a function called "remove" should perform a delete operation and not PUT.
I'm trying to build a simple webapp that will have a list of patients, displaying their vital signals values (such as heart rate, spo2 levels, etc...): Im using react for the frontend and Im trying to use setInterval to update said values periodically. However Im having some trouble with that, the list of patients in state is updated, but the new values are not displaying.
I already tried something similar, just like below and this one works fine, so im really clueless about what the problem might be:
Edit: I can see that the state is updated in the console.log, I just cant get those values to be displayed on the screen each second
As you are getting patients details from api already you can directly update state like this, no need to maintain separate array for that.
.then(res=>{
this.setState({patients: res.data.patient})
})
In an interview, an interviewer asked me that where should you make API-hits in a simple react application? Meaning in which life-cycle method in a Class-Component. I knew the answer to be ComponentDidMount - because it is the first life-cycle method where we get complete rendered dom meaning dom is now ready!
Then he asked, but why NOT in comonentDidUpdate?
Now, I told him what I had read somewhere, I don't know the exact answer of this -- except ComponentDidMount runs first, so make it there.
Now, can someone tell me if my answer was correct? Or should we make API-hits in ComponentDidUpdate()?
I am confused. Kindly, someone explain with reasoning? Thanks in Advance!
It depends on when you want to call the API:
If an API call is done only once then do componentDidMount
If after render based on some state, you want to fetch data again then do it in componentDidUpdate
EDIT:
Same scenarios can be handled within functional components using useEffect hook as follows:
1- Only runs the first time when the components render same as componentDidMount:
useEffect(() => {
// Run only once when the component renders
}, []); // Pass empty array as dependencies
2- Run every time when component renders either by props change or by local state change same as componentDidUpdate without comparing previous and current props:
useEffect(() => {
// Run every time the component re-renders including the first time
}); // Do NOT pass array dependencies
3- Run only when particular props change, same as componentDidUpdate but with props comparison:
useEffect(() => {
// Run only when the component prop1 and prop2 changes
}, [prop1, prop2]); // Pass props as array dependencies
Reference: Using the Effect Hook
Lets take an example scenario.
You have a profile page and it has a text box which allows you to update tags.
You do a fetch for the whole profile in the componentDidMount to get all the details and show the content.
And then componentDidUpdate will have to be used for something like the update on tags, lets say you do a fetch to get tags based on the user input for every 3 letters the user type. then you use componenDidUpdate to check the state and do the call.
If you think of the same in functional components we'll have to use useEffect.
useEffect(()=>{},[]);
See the array of dependecies, if you pass an empty array it would act similar to componentDidMount.
And the componentDidUpdate
useEffect(()=>{},[tagText]);
Here the effect will run only when a change it done to the tagText, but the componenDidUpdate would be different as you will have to compare the previous state and decide whether the text is updated.
According the Official React Documentation (Link):
componentDidMount
componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
This method is a good place to set up any subscriptions. If you do
that, don’t forget to unsubscribe in componentWillUnmount().
componentDidUpdate()
componentDidUpdate() is invoked immediately after updating occurs.
This method is not called for the initial render.
Use this as an opportunity to operate on the DOM when the component
has been updated. This is also a good place to do network requests as
long as you compare the current props to previous props (e.g. a
network request may not be necessary if the props have not changed).
Check out this link for a complete big picture. This will be handy while learning react.
I am struggling with using Web socket in ReactJS.
I have followed this solution: https://stackoverflow.com/a/60161181/12962511
This solution works pretty good!
However, I wonder why onmessage is in useEffect.
I tried onmessage in the useEffect with [] which is componentDidMount. This results reset my states but not starting the function from the beginning because useEffect with [] did not get triggered in this case.
So my question is:
The difference between put onmessage in useEffect with [] or in just useEffect.
The necessity of useRef in react Hooks websocket (I tried both ways and it looks pretty same on network console.) - I know useRef prevents making websocket every re-render.
I have stuck this issue for all day long. :(
Please help me.
Thank you so much!
useEffect without dependencies will be triggered every render. As you need to make subscription only once, it should be with empty decencies [].
In your example, useRef is used only to pause listening to messages via websocket. If you don't need this logic, you able to not use it.
As you can tell from my title Im not even sure what to call the problem.
I created an example here in code sandbox
https://codesandbox.io/s/interesting-poitras-5bcuv?file=/src/Demo.js
If its a wait for the value to be set problem, I've read I need to implement a loading state of some sort? I've attempted that here:
https://codesandbox.io/s/blissful-antonelli-tu624?file=/src/Demo.js
but can't seem to get it to work, and I don't know if I am even on the right track.
I've been working with react for a couple of months now, and one of the things I don't completely understand is:
It seems like the code runs multiple times, the first time it will pass the default state of {} as value to my demo component, the state will be set and it will pass the actual value in.
My app is crashing before the actual value gets passed in because of the split.
In the past, I've managed by just throwing a bunch of if and && statements at the problem like below, but is this the best way?
const split = props.values.home && props.values.home.split("-")
You need to have a safe check there. Your problem is a normal js problem, you cannot access a prop of an undefined type
just change: props.values?.home?.split("-") || []; (as stackblitz supports optional chaining)
and it will work as you expect