I am trying to fetch data in a functional React component using useEffect (since the function is asynchronous) and I compute and return the data in h2 tags that was fetched in this component. However, I want to fetch the data when in another component (App.js) I hit the enter key. I have an enter key handler which calls a useState which I believe should re-render the component but since the useEffect is in another component, I am not getting the calling of the useEffect as I intend. What is the best method to press the Enter key and have useEffect in another component run?
function handleKeyDown(event){
if(event.key === 'Enter'){
//this setHeadingText is a useState variable which should re-render in App.js
setHeadingText(name);
}
CodePudding user response:
It sounds like your useEffect
is specifying an empty dependency array (instructing to run only once):
useEffect(() => {
//fetch some data
}, []); // This empty array ensures it only runs 1 time
Have a look at this section in the docs: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
If your second component has access to your headingText
state, try specifying your headingText
as a dependency to the useEffect
, and any changes to it should trigger your useEffect
useEffect(() => {
//fetch some data
}, [headingText]); // Only re-run the effect if headingText changes
Alternatively, remove the dependency array from your useEffect
.
Note: this will cause the useEffect
to run on every re-render
useEffect(() => {
//fetch some data
}); // run every time the component re-renders
CodePudding user response:
Now that I have understood properly, I think this is the solution you wished for:
- The
headingText
value that is being updated in yourApp.jsx
component should be passed down to yourChild
component with the help ofprops
. So use<Child headingText={headingText} />
while loading the Child component in yourApp.jsx
. - Inside your
Child
component, receive the value like thisfunction Child(props)
orfunction Child({ headingText })
if you have more values to pass, prefer props. - Now you can easily access the changes in value made in your
App
component inside yourChild
component with the help ofprops.headingText
orheadingText
respective to the way you defined yourChild
in point 2. - To re-render your
Child
component, you will now use theuseEffect
hook with its dependency set toheadingText
, like:
React.useEffect(() =>
{
// Code for refetching
}
, [headingText]); // or props.headingText if your Child component uses (props)
For example: CodeSandbox
Hope that helps you!