Home > Back-end >  React: Trying to set state via useEffect using local JSON data
React: Trying to set state via useEffect using local JSON data

Time:12-24

I have a functional component that uses useState to set the mtvData state (via setMtvData).

However, I'm trying to call setMtvData in useEffect so that the mtvData state will have the json data and that json data will be passed to the Chart component.

But so far the Chart component just gets an empty string:

import Chart from './Chart.js';
import {useState, useEffect} from 'react';
import myjson from './data/myjson.json'

export default function App() {

  const [mtvData, setMtvData] = useState([]);

  useEffect(() => {
    setMtvData([...myjson]);
  },[])

  return (
     <Chart data={mtvData} />
  )

}

CodePudding user response:

Why are you setting the state on mount instead of initializing the state with your json?

import Chart from './Chart.js';
import {useState, useEffect} from 'react';
import myjson from './data/myjson.json'

export default function App() {

  const [mtvData, setMtvData] = useState([...myjson]);

  return (
     <Chart data={mtvData} />
  )

}
  • Related