-1

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;
gr1mberg
  • 21
  • 1
  • 2
    Does this answer your question? [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Brian Thompson Oct 28 '21 at 19:39

2 Answers2

1

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.

punjira
  • 818
  • 8
  • 21
0

I suggest you should use states

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

};}
AkhanIskak
  • 52
  • 3