score:3
You can return a new Promise
from myFunction
that is resolved in the callback to setState
.
Then you can use async
/await
in your otherFunction
.
myFunction = () => {
return new Promise(resolve => {
let originalFoo;
this.setState(
state => {
originalFoo = state.foo;
return {
foo: "bar"
};
},
() => resolve({ originalFoo, newFoo: this.state.foo })
);
});
};
otherFunction = async () => {
var originalValue = await myFunction();
};
score:0
My implementation below does not use async/await. If you need to wait until setState
is complete, you're probably better off going with Tholle's answer. However, mine is a tad cleaner if you simply want to return an object with values irrespective of whether the state has been fully set.
myFunction = () => {
let returnData;
this.setState(state => {
// do some stuff here
returnData = { originalBar, newBar: state.foo };
return {
foo: "bar"
};
});
return returnData;
}
otherFunction = () => {
var originalValue = this.myFunction();
}
However, I would not recommend this, and instead I would try not to use a functional callback in this.setState
.
Perhaps you could do something like this?
const originalBar = this.state.foo; // or whatever it might be
const newBar = "bar";
this.setState({ foo: newBar });
return { originalBar, newBar };
Quite a bit shorter, and quite a bit more elegant.
score:0
Looks like you want to acces the previous state and the current state. Rather than using setState
to do something that is not intended for it, you can use life cycle methods in react which provide you with the previous state as well as previous props depending upon your usecase.
componentDidUpdate(prevProps, prevState, snapshot){
...
}
or
getSnapshotBeforeUpdate(prevProps, prevState){
...
}
Source: stackoverflow.com
Related Query
- Async return value from setState
- document is not defined when attempting to setState from the return of an async call in componentWillMount
- How use async return value from useEffect as default value in useState?
- Redux Toolkit w/ TypeScript: how can I properly type the return value from an async thunk
- Do I always need to return a value from a redux middleware?
- Async arrow function expected no return value
- How fix this warrning warning Array.prototype.map() expects a return value from arrow function array-callback-return?
- Is there way to get return value from reducer action? (in React-Native)
- How can a function value is displayed in a HTML tag with a return value from addEventListerner click?
- get latest state value after setState hook within async await block in react
- How to create array from state value and setstate after removing duplicates in reactjs
- Determine the type of a return value from dispatch
- React - Return function value to setState
- React setState callback return value
- How to assign return of async value to initial state of reducer?
- Using Array.find() to try and dynamically grab a specific object value and return it based on Object name, nothing returning from function
- Not getting returned value from async await function
- React Flux - Return value from flux dispatcher / store
- Get object array from axios and using return value call another axios function and append the output to first result
- Return a value from a setTimeout
- Passing a return value from one component to another
- Return a value from a modal with multiple buttons (React)
- Return boolean value from Material UI Radio to use in Yup .when Validation
- return value is not rendering when returned from inside the handleclick() function in react
- setState when receive props from parent component which fetch async data
- Array.prototype.map() expects a return value from arrow function array-callback-return
- How to return a value from Firebase to a react component?
- await not waiting for async function to return value
- Return value from child component to parent component React
- React, return boolean value from custom hook
More Query from same tag
- Next js pass JSON object from one page to another page props when navigating programmatically
- Promise all and correctly update the state using React.js
- Inline Styling Individual React Components
- MUI: Avoid line break between Typography components
- Using Form and Input elements correctly
- How to use Material UI from component library in a project with Material UI already?
- How to extends classes in material UI createStyles
- Currying React Parent Functions for Child
- Add images to DOM following cursor position
- Spring method with React front
- How to update key value inside array when state changes?
- Reactjs how to use multiple filters and dropdown input
- Add style to bundled code using webpack
- Local fonts to scss file in react
- Cannot test redirecting in react router with enzyme
- React Inserting a compoent into a table between 2 rows dynamically
- How to get current position(X Y) of div that i am dragging around in react?
- How to conditionally render commas and periods?
- Using querySelectorAll instead of querySelector for testing with toBeInTheDocument
- How to disable tslint check in VScode?
- Testing of Nested React components using React-Test-Renderer
- React HOC ESLint Error: props spreading is forbidden
- parse error handleDismissClick = e =>
- styled-components is saying wrapped styled() around your React component (Component)
- React useState changes all elements in an array in array of objects
- Ruby on Rails "support for the experimental syntax 'jsx' isn't currently enabled"
- TypeError: Cannot read property 'onSelect' of undefined
- TypeError: _this2 is undefined REACTJS
- React force componentDidMount
- In ReactJS opening pdf in a new tab triggers browser's popup warning