score:0
it is a normal behaviour setstate will produce only a single re-render at the end of the event even if you used await, try to add a console.log inside your component you will see returnedmessage moved to 'new'
// app.js
import react from "react";
import useemail from "./useemail";
export default function app() {
const { returnedmessage, send } = useemail();
console.log("returnmessage post", returnedmessage); // in last render it will be new so it will change the view
const run = async () => {
console.log("returnmessage pre", returnedmessage);
await send();
};
return (
<div classname="app">
<h2>click and wait for 1 second</h2>
<button onclick={run}>click me</button>
<h2>returned message:</h2>
<p>{returnedmessage}</p>
<button onclick={() => window.location.reload()}>
reload to test again
</button>
<p>
it prints "new", but logs "old"
<br />
even if i await send()...?
</p>
</div>
);
}
score:0
one thing that i noted, from your custom react hook, you are returning an async
function.
which is this:
async () => {
// fake fetch
const whatever = await fetch(
"https://jsonplaceholder.typicode.com/todos/1"
);
setreturnedmessage("new");
};
and within your app component, you are accessing the custom hook where send
is pointing to this async
function. right?
now when you are calling your async function you are trying to do:
await send();
why await
here again, since we already have an await
inside of our function.
when you do this you are basically waiting for a promise()
here, since every async
function returns a promise even when nothing is returned.
i feel the implementation of custom hook should change or calling the hook has to be different.
on top of this setstate()
is itself an asynchronous action. that is not in our control to tell when the state will update :)
score:1
you can do the job using useref
.
it seems you can't access the updated value without running the hook again.
with useref
you'll get a reference and you can access the data at any time, without running the hook again.
// useemail.js
export default function useemail(message) {
const messageref = react.useref("old");
const send = async () => {
// fake fetch
const whatever = await fetch(
"https://jsonplaceholder.typicode.com/todos/1"
);
messageref.current = "new";
};
return {
messageref,
send
};
}
// app.js
export default function app() {
const { messageref, send } = useemail();
const run = async () => {
console.log("returnmessage pre", messageref.current);
await send();
console.log("returnmessage post", messageref.current);
};
return (
<div classname="app">
<h2>click and wait for 1 second</h2>
<button onclick={run}>click me</button>
<h2>returned message:</h2>
<p>{returnedmessage}</p>
<button onclick={() => window.location.reload()}>
reload to test again
</button>
<p>
it prints "new", but logs "old"
<br />
even if i await send()...?
</p>
</div>
);
}
score:1
you have 2 async functions in your custom hook.
- your fetch (which one you await)
setstate
so even if you await for the fetch, your setstate is still asynchronous:
console.log("returnmessage pre", returnedmessage); //old
- fetch
- await fetch to complete
- fetch complete
- trigger setstate
- function
send()
returnsundefined
(because no return is defined) console.log("returnmessage post", returnedmessage); //old
- state is updated (async setstate is complete)
returnedmessage
is updated- component re-renders
if you want to have actions depending on when returnedmessage
is changed, you'll have to use useeffect
in your component
useeffect(() => {
if (returnedmessage === "old") return; // do nothing here
// returnedmessage !== "old" so assume it's "new"
// do something...
}, [returnedmessage]);
Source: stackoverflow.com
Related Query
- React custom hook: can't get an async function
- Custom react hook with useeffect, cant use in non-component function
- React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing
- React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function
- React Hook "useEffect" is called in function "shoes" which is neither a React function component or a custom React Hook
- React Hook "useContext" is called in function "age" which is neither a React function component or a custom React Hook function
- React Hook "useState" is called in function "setResults" which is neither a React function component or a custom React Hook function
- React Hook "useState" is called in function "test" which is neither a React function component or a custom React Hook function
- React Hook "useState" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function
- Clean up async function in an useEffect React hook
- when is the useEffect hook clean up function get called in react
- React Hook "useDispatch" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function
- React Custom Hook set function returned is not a function
- get latest state value after setState hook within async await block in react
- React Hooks must be called in a React function component or a custom React Hook function
- React Hook "useState" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function
- React Hook is called in function that is neither a React function component nor a custom React Hook function
- Custom React hook with function as arguments
- React Hook "useStyles" is called in function which is neither a React function component or a custom React Hook function
- Function called from a react custom hook returns 'is not a function'
- React Hook is called in function "onSubmit" which is neither a React function component or a custom React Hook function
- React Hook "useParams" is called in function "fetchMentors" that is neither a React function component nor a custom React Hook function
- React Hook "useTranslation" is called in function "getMyMenu" that is neither a React function component nor a custom React Hook function
- Cleaning up after AJAX function in custom React hook
- Failed to compile React Hook "useQuery" is called in function "home" which is neither a React function component or a custom React Hook function
- React Hook is called in function which is neither a React function component or a custom React Hook function
- @apollo/client error-React Hook "useQuery" is called in function which is neither a React function component or a custom React Hook function
- How to get helper function returning promise for React hook function
- React returning a function in a custom hook, whose internal hook returns an object
- Call custom React async hook within a component and se it's state again
More Query from same tag
- How to pass function as props from functional parent component to child
- Infinite Re-rendering of React Functional Component using Axios and useState/useEffect?
- How to toggle master CSS file in nextjs?
- Usability of Protractor outside of AngularJS
- How do I implement nested routing in react properly
- Hiding API Key in React
- Why we use Bind method on onClick event
- onClick not invoked when clicking on sidebar
- Webpack resolve.alias not working in node/server side
- button type='submit' with onClick
- Resizing Material-UI <TextField> causes cursor to exit its container
- unexpected react component state value change
- Avoid rerender in React caused by objects literal : how to do with variables in the object?
- Passing props from component to componet using react hooks
- Parent component unnecessarily re-rendering child on parent state change
- Where should I place a script in React/Redux?
- How to create admin route using react router v 6
- React input form without form component?
- Unable to test post methods with Jest due to error can not read mockImplementation of undefined
- "Successful" Netlify Form Submissions Don't Show in Dashboard
- reduxForm - initialValues did not apply after update
- How do I set the onClick in the navbar of material-ui?
- npm install bootstrap@4.0.0 command gives ENETUNREACH error
- How update Apollo Cache with a lot of active queries
- ReactJs: refs is not defined (no-undef)
- How to use TypeScript generics with React render props
- The * selector in react/next.js
- JSX element type 'App' is not a constructor function for JSX elements. Types of property 'setState' are incompatible
- React, TypeScript: How define the parameters of handler in a child component?
- web3js intercepting when metamask connects manually