setState/use State in external function react

Home / Uncategorized / setState/use State in external function react

Question:
Considering this pseudocode:
component.js

import {someFunc} from "./common_functions.js"

export default class MyComp extends Component {
constructor(props) {
super(props);

this.someFunc = someFunc.bind(this);

this.state = {…};
}

_anotherFunc = () = > {
….
this.someFunc();
}

render() {

}
}
common_functions.js
export function someFunc() {
if(this.state.whatever) {…}
this.setState{…}
}
How would I bind the function someFunc() to the context of the Component? I use it in various Components, so it makes sense to collect them in one file. Right now, I get the error "Cannot read whatever of undefined". The context of this is unknown…


Answer:
You can’t setState outside of the component because it is component’s local state. If you need to update state which is shared, create a store (redux store).

In your case, you can define someFunction at one place and pass it the specific state variable(s) or entire state. After you are done in someFunction, return the modified state and update it back in your component using setState.
export function someFunc(state) {
if(state.whatever) {…}
const newState = { …state, newValue: whateverValue }
return newState
}

_anotherFunc = () = > {
….
const newState = this.someFunc(this.state);
this.setState({newValue: newState});
}
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *