Reputation: 195
I have a component useRandomizer
with random functions which I want to access inside main App.js
in app.js
I have following hook:
import useRandomizer from './components/useRandomizer'
...
useEffect(
() => {
let rndData = useRandomizer()
random component has following structure which gives me error React Hook "useRandomizer" cannot be called inside a callback.
const useRandomizer = () => {
let rndData = []
rndData.push(getRandomName())
return rndData
}
export default useRandomizer
However if I retructure export like shown below, then these can be used in app,js
export default {
getRandomName,
... other random functions
}
but this on the other hand give me more problems in app.js
(code below). It runs ALL of random runction as many times as I've put any them. E.g get random name and random name two and random name three -> instead of pne array with 3 names it gives me 3 arrays with 3 names.
import useRandomizer from './components/useRandomizer'
...
useEffect(
() => {
let rndData = []
rndData.push(useRandomizer.getRandomName())
rndData.push(useRandomizer.getRandomNameTwo())
rndData.push(useRandomizer.getRandomNameThree())
edit1
this useEffect is a dispatch
part of useReducer
like this
const Reducer = (state, action) => {
... do stuff
}
const [Dispatch] = useReducer(Reducer, somestate)
useEffect(
() => {
Dispatch(somestate)
let rndData = useRandomizer()
edit2
since reducer was concatenating arrays the goal was to push random values inside newly created ones. So instead of having a long code in app.js
I've decided to move it into new component.
Upvotes: 1
Views: 2466
Reputation: 195
The problem here was using export
without curly braces {}
So that's how my function has to look like:
const useRandomizer = () => {
let rndData = []
rndData.push(getRandomName())
return rndData
}
export default {useRandomizer} //was: export default useRandomizer
hence abovementioned dispatch
code works fine now
import useRandomizer from './components/useRandomizer'
const Reducer = (state, action) => {
... do stuff
}
const [Dispatch] = useReducer(Reducer, somestate)
useEffect(
() => {
Dispatch(somestate)
let rndData = useRandomizer()
Seems like adding {}
drastically afftects import/export syntax.
Here you can read more what exactly changes
Upvotes: 1