James
James

Reputation: 3815

Importing initialisation functions in ReactJS / React-Native

I am currently refactoring a project by abstracting all init functions outside of the actual React component.

These init functions simply hydrate the Redux store and set some cookies.

Let's say I store them in a file called AppInit.js, as follows:

..

hydrateRedux = () => {
  //
}

setCookies = () => {
  //
}}

..

What is the approach I should take to be able to call this initialisation file to run all the functions?

I was thinking of doing some like an actions file, however I prefer if I just call the file to run the functions automatically rather than calling them one by one...

Upvotes: 1

Views: 337

Answers (1)

Michal
Michal

Reputation: 5220

This can be your init.js file:

// init.js
export const firstInitFunction = () => console.log('init first')

export const secondInitFunction = () => console.log('init second')

export const thirdInitFunction = () => console.log('init third')

This can be your index.js file (or whatever file needs to call functions from init.js:

// index.js file
import * as inits from './init.js'; 

inits.forEach(init => init())

There are many other ways to do this. This one is probably the most straightforward.

You can also execute the inits.forEach(init => init()) inside the init.js file. That way your index.js file can look like this:

// index.js file
import './init.js'

Upvotes: 1

Related Questions