Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access state in function which is in another file

today I’ve finished my first React App - Calculator.

I though it will be better to have App.js clean and place all of the logic functions in separated file Logic.js and also all of the design functions (changing output font size depending on length of number or button on click animations) in for example Effects.js.

Problem occured when i took functions ,placed them in new file (of course exported them and also imported them in app.js).

Error says that setNumber(method which i call when i want to work with state),

number.firstNumber (firstNumber state which holds first clicked number),

And every state which im calling in this file (functions or conditions) is not defined ,so it means this file has no access to App.js state. Is there any way I can keep these functions separated and don’t have to rebuild whole app so I can achieve clean code ?

App.js creating states with which I work in these functions

const [number, setNumber] = useState({
firstNumber: "",
secondNumber: "",
operator: "",
result: "0",
displayed: "0",
cButton: "AC",
cButtonCheck: false,
numToReset: false,
sizeOfOutput: "1em",
isOrange: false
});

Example of function in new file which gets error of setNumber is not defined

function turnOnOrange(operator) {
if (number.isOrange === false)     {
  setNumber(prevState => ({
    ...prevState,
    isOrange: true,
    whichOrange: operator
  }));
  operator.className = "orangeActivated";
}
}

Thanks, link so you can see whole code

https://codesandbox.io/embed/youthful-platform-n6lvs?fontsize=14&hidenavigation=1&theme=dark&codemirror=1

like image 561
Pinnci Avatar asked Oct 26 '25 00:10

Pinnci


1 Answers

You should return these variables from the function and export the function not vice versa.

What you're trying to do is called custom hooks I'll give you an example in which you can reflect on:

useMyFirstCustomHook.js file
import React, { useState } from 'react';

const useMyFirstCustomHook = () => {
  const [count, setCount] = useState(0);
  // do some stuff
  return { count, setCount };
};

export default useMyFirstCustomHook;

App.js file
//..
import useMyFirstCustomHook from 'path/to/useMyFirstCustomHook';
//..
const { count, setCount } = useMyFirstCustomHook();
console.log(count);
like image 74
Mohamed Wagih Avatar answered Oct 28 '25 13:10

Mohamed Wagih