3

I am creating an animations using Adobe After Effects and React Lottie and I have many json files generated by Bodymovin extension. I am importing files in that way:

import * as initial from './white_bird.json';
import * as hoverOn from './white_bird_hover_on.json';
import * as hoverOff from './white_bird_hover_off.json';

But, when I have e.g. 6 other components that look identically but differ from each other only with imported files. How can I write those lines upper in something like this:

const data = {
    initial: import * as initial(`./${some_param}.json`),
  };

Note that I must import it like '* as' in another way this doesn't work

Freestyle09
  • 4,894
  • 8
  • 52
  • 83

2 Answers2

7

You could use Dynamic import:

useEffect(() => {
  async loadData() {
    const data = await import(`./${some_param}.json`);
    setInitial(data);
  }

  loadData();
}, [])

and use Promise.all if you have multiple requests:

useEffect(() => {
  async loadData() {
    const [initalData, hoverOnData, hoverOffData] = await Promise.all([
      import(`./${bird}.json`),
      import(`./${bird}_hover_on.json`),
      import(`./${bird}_hover_off.json`)
    ]);

    setInitial(initalData);
    setHoverOn(hoverOnData);
    setHoverOff(hoverOffData);
  }

  loadData();
}, [])
Fraction
  • 11,668
  • 5
  • 28
  • 48
0

I found a solution, import returns a Promise and later I can easily set my data from file to state and now it works perfect.

const [initial, setInitial] = useState(null);
const [hoverOn, setHoverOn] = useState(null);
const [hoverOff, setHoverOff] = useState(null);

  useEffect(() => {
    import(`./${bird}.json`).then(data => setInitial(data));
    import(`./${bird}_hover_on.json`).then(data => setHoverOn(data));
    import(`./${bird}_hover_off.json`).then(data => setHoverOff(data));
  }, []);
Freestyle09
  • 4,894
  • 8
  • 52
  • 83