Home > database >  How to use a variable outside of a function in React.js
How to use a variable outside of a function in React.js

Time:10-29

I'm trying to find a way to use the variable outside of a function in React. How can I use the variable "testing" outside of the reducer function?

const initialState = {count: 0};

function reducer(state, action) {
    let testing = state.count;
    switch (action.type) {
      case 'increment':
        return {count: state.count   1};
      case 'decrement':
        return {count: state.count - 1};
      default:
        throw new Error();
    }
  }


const global = testing;

CodePudding user response:

I suggest you should use states

export default class App extends Component {
constructor(props) {
    super(props);
}
state = {
    testing:null

};}

CodePudding user response:

You can simply define your testing variable outside of your function:

let testing;

function someFunc(someInput) {
    testing = "some data";
}
const global = testing;

Or you can return it inside the function:

function someOtherFunc(input){
    let testing = "some data"
    return testing;
}
const testing = someOtherFunc("some input");

But since your function is a reducer it really should not cause any side-effects which is exactly what you'r trying to do. Updating your question with more explanation might help find other alternative to what you are trying to reach.

  • Related